【发布时间】:2020-03-16 06:58:56
【问题描述】:
我有一个类似的获取请求
fetch(`http://localhost:4000/test`, {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json'
}
})
.then(result => console.log('success'))
.catch(error => console.log('error', error));
还有一个 nodejs express 路由器(express-promise-router)用于请求
this.router.get('/test', (request: Request, response: Response) => {
response.status(200).send({'status': 'ok'});
});
当调用 fetch 时记录成功。所以这很好。 但是当我将nodejs路由器功能更改为异步时
this.router.get('/test', (request: Request, response: Response) => {
return asyncFunction().then(result => response.status(200).send({'status': 'ok'}));
});
提取被取消,控制台日志显示TypeError: Failed to fetch。
当我使用浏览器 URL 或 Postman 调用 /test api 时,我得到了成功的结果。 我无法弄清楚为什么提取失败。 (也用 Axios 试了一下,结果一样)。
【问题讨论】:
-
你把路径从“/test”改成“/login”了吗?
-
你在哪里调用 fetch 在 asyncFunction
-
@ManjeetThakur 不抱歉,它也是“/test”
-
@YouBee asyncFunction 只是一个例子。路由器 url 被 fetch 调用。由于路由器是 express-promise-router,因此使用 Postman(或浏览器 URL)可以得到正确的响应。
标签: node.js express asynchronous fetch