我是 NodeJs/Express 的新手。我正在尝试创建一个 API,它将依次调用现有的 API,该 API 基本上会创建经过一些修改的产品。基本上我调用的 API“产品”使用 POST 方法。基本上期望数据以 JSON 格式传递。但在这里我从目标 API 收到错误消息,指出 body 未传递。
let json = {"id": "", "name" : ""};
app.get('/createProduct/:product_id', function (req, res) {
let url = 'https://somewebsite/api/products'
json.id = req.params.product_id;
req.headers['token'] = getToken();
req.headers['timestamp'] = getTimeStamp();
req.body = json;
req.pipe(request(url)).pipe(res);
});
我错过了什么吗?
最佳答案
在这种情况下,您不一定需要将 req 对象通过管道传递给请求调用,您只需进行 request.post 调用,您仍然可以通过管道传递输出,我认为它会给您结果愿望:
let json = {"id": "", "name" : ""};
app.get('/createProduct/:product_id', function (req, res) {
let url = 'https://somewebsite/api/products';
// Create headers for outgoing call.
let headers = {
token: getToken(),
timestamp: getTimeStamp()
}
// Populate the json.id value.
json.id = req.params.product_id;
request.post({ url, headers, body: json, json: true }).pipe(res);
});
同样出于测试目的,我建议您创建一个 POST 监听器来查看传递给服务的内容,您可以轻松地以 Express 方式执行此操作:
app.post("/post_test", bodyParser.json(), (req, res) => {
console.info("/post_test: headers:", req.headers);
console.info("/post_test: body:", req.body);
res.status(201).send("All good");
})
要使用此功能,只需将 app.get 调用中的 url 更改为:
http://localhost:<port>/post_test
记得改回来!
关于node.js - 使用 Express 传递 json 正文调用现有 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073496/