【发布时间】:2021-02-03 20:30:35
【问题描述】:
我有一个简单的 Express 应用程序,其中包含几条路线。特别是一条路线是 POST 路线。在此 POST 路由中,我尝试向第三方 API 进行 POST,并在我的实际 POST 响应中使用来自此第三方 API 响应的数据。该应用程序如下所示:
const express = require('express');
const axios = require('axios');
const app = express();
...
app.post(
'/api/links',
(req, res, next)=> {
const data = req.body;
axios.post('https://third.party.api.com/api/v1', data, headers)
.then(data => res.json(data.data))
.catch(err => res.send(err));
next();
}
)
我定义的 GET 请求有效,但 POST 无效。我正在使用 axios 在/api/links POST 中间向第三方 API 发送 POST。我希望我的端点在成功时从这个第三方 API 返回数据,这就是我拥有res.json(data.data) 的原因。我在 GET 路由中使用 res.json 没有问题,但是当我在 POST 路由中使用它时,我从 res.json() 行收到错误 [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client。我试过去掉 axios 并改用普通的https,但我仍然得到同样的错误。我做错了什么?
【问题讨论】:
标签: node.js express http axios