I am new to NodeJS
and I am practicing a small project. I have this code which sends request to my NodeJS
express server via API endpoint.
var XHR = new XMLHttpRequest();
var merchants = ['f6ea7039-de8e-4403-bb63-d348dd502dc8', 'c2a08bfa-db18-4e08-8a08-f4e04dea7e58',
'e02ed2a4-06f4-403b-ad1e-f72b55e0681d'];
//set up the transfer request
XHR.open('POST', apiUrl + '/transfer', true);
XHR.setRequestHeader("Content-Type", "application/json; charset=utf-8");
XHR.withCredentials = true;
var data = JSON.stringify({
//merchantId: merchants[(Math.floor((Math.random() * 200))/100)],
merchantId: 'f6ea7039-de8e-4403-bb63-d348dd502dc3',
amount: (Math.floor((Math.random() * 1000) + 100)/100),
currency: 'EUR',
description: 'Book
// Define what happens on successful data submission
XHR.addEventListener("load", function(event) {
console.log(event);
// execute callback once response is received
if (event.target.status === 200) {
done(XHR.response);
}
});
XHR.send(data)
and in my server side I have this code:
function getMerchantName(query) {
return new Promise(function(resolve,reject){
pool.query(query, [tr.merchantId], function(error, result){
// error ? reject(error) : resolve(result);
if(result[0]){
return resolve(result);
}else{
return reject(error);
}
});
});
}
getMerchantName(sql)
.then(result => {
tr.secondaryName = result[0].mName;
console.log("Secondary Name: ",tr.secondaryName);
conn.release();
getUrl();
})
.catch(function(error){
console.log('Rejected', error);
// res.send(400, {message: 'Merchant Not Found'});
res.status(403).send({message: 'Merchant Not Found'});
});
So when the merchant id
is not found, I throw (via promise's catch) a response to res.status(403).send({message: 'Merchant Not Found'});
I can only access the error status through XHR.addEventListener
load event but not the response body. How can I access this response body to display in client side?
I think you should use express bodyparser :
during init:
app.use(bodyParser.json())
and here is an example request handler:
app.get('/', (req, res) => console.log(req.body))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.