1.Coding style
(1)nodejs: express での戻り値の渡し方
(2)fetch, XMLHttpRequestでのrequest
2.exprssでの戻り値の渡し方
router.post('/send', async function(req, res) {
const {client_host} = req.body;
let code, err;
[ code, err ] = await to_client.connect(client_host);
if(code == 500) {
let rt = JSON.stringify({"error":"ECONNRESET"});
return res.status(400).end(rt);
}
if(code !== 200) {
let rt = JSON.stringify({"error":""});
return res.status(400).end(err);
res.json({
err : 0,
msg : status.document_uuid
});
}
3.request
(1) fetch
function evt_send(document_uuid) {
const params = {
document_uuid : document_uuid
};
const url = '/api/invoice/send';
const opts = {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(params)
};
let response;
try {
response = await fetch( url, opts);
} catch(err) {
throw err;
}
let res;
try {
res = await response.json();
} catch(err) {
throw err;
}
if(response.status == 200) {
this.API.refresh();
} ekse {
alert("送信できませんでした.\n"+res.err);
}
}
(2) XMLHttpRequest
function evt_send(document_uuid) {
const params = {
document_uuid : document_uuid
};
const ajax = new XMLHttpRequest();
ajax.open('POST', '/api/invoice/send');
ajax.setRequestHeader('Content-Type', 'application/json');
ajax.responseType = "json";
ajax.send(JSON.stringify(params));
ajax.onload = () => {
const res = ajax.response;
if(ajax.status == 200) {
this.API.refresh();
} else {
alert("送信できませんでした.\n"+res.err);
}
}
}