我需要创建一个名为“getLocationById”的业务级函数,它通过 REST API 从远程服务器检索一些数据。然后由路由器调用此函数以在网页上显示数据。
如果 fetch 调用成功,则 json 结果作为 Promise 返回。但是,如果 fetch 发现错误,例如远程服务器没有响应或响应 500 错误,应该向路由器返回什么?
此外,路由如何响应错误?
const fetch = require('node-fetch');
const p_conf = require('../parse_config'); // Configuration
const db = {
getLocationById: function(locId) {
fetch(`${p_conf.SERVER_URL}/parse` + '/classes/location', { method: 'GET', headers: {
'X-Parse-Application-Id': p_conf.APP_ID,
'X-Parse-REST-API-Key': p_conf.REST_API_KEY
}})
.then(res1 => return res1.json()) // RETURN A PROMISE ON SUCCESS
.catch((error) => {
console.log(error);
**WHAT TO RETURN TO THE ROUTER ON ERROR HERE?**
});
}
};
编辑:
const db_location = {
getLocations: function() {
//res.send("respond with 'locations' router.");
fetch(`${p_conf.SERVER_URL}/parse` + '/classes/GCUR_LOCATION', { method: 'GET', headers: {
'X-Parse-Application-Id': p_conf.APP_ID,
'X-Parse-REST-API-Key': p_conf.REST_API_KEY
}})
.then(res1 => res1)
.catch((error) => {
console.log(error);
return Promise.reject(new Error(error));
})
}
};
在路由器中:
router.get('/', function(req, res, next) {
db_location.getLocations()
.then(r => res.send(r.json())) // WHERE AN ERROR WAS THROWN
.catch((err) => {
console.log(err);
return next(err);
})
});
引发了以下错误:
TypeError: Cannot read property 'then' of undefined
上.then(r => res.send(r.json()))
进一步编辑:
然后我做了以下更改。
业务层
getLocations: function() {
// According to node-fetch documentation, fetch returns a Promise object.
return fetch(`${p_conf.SERVER_URL}/parse` + '/classes/GCUR_LOCATION', { method: 'GET', headers: {
'X-Parse-Application-Id': p_conf.APP_ID,
'X-Parse-REST-API-Key': p_conf.REST_API_KEY
} });
}
路由器端:
router.get('/', function(req, res, next) {
db_location.getLocations()
.then(r => {
console.log("r.json(): " + r.json());
res.send(r.json())})
.catch((err) => {
console.log(err);
return next(err);
})
});
然后抛出了一个新错误:
(node:10184) UnhandledPromiseRejectionWarning: TypeError: body used already for: http://localhost:1337/parse/classes/GCU
R_LOCATION
at Response.consumeBody (C:\Work\tmp\node_modules\node-fetch\lib\index.js:326:30)
at Response.json (C:\Work\tmp\node_modules\node-fetch\lib\index.js:250:22)
at db_location.getLocations.then.r (C:\Work\tmp\ExpressApps\express-parse-server\routes\locations.js:30:13)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
(node:10184) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing ins
ide of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejectio
n id: 5)
(node:10184) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.
我相信 fetch 函数返回了一个 Promise 对象,调用函数可以从路由中接收该对象?