Node.js 使用快速传递json体调用现有API

Node.js 使用快速传递json体调用现有API,node.js,rest,express,Node.js,Rest,Express,我不熟悉NodeJs/Express。我正在尝试创建一个API,它将调用一个现有的API,该API基本上创建了经过一些修改的产品。基本上,我调用的API“产品”使用POST方法。它基本上期望数据以JSON格式传递。但在这里,我从目标API中得到一个错误,表示body未被传递 let json = {"id": "", "name" : ""}; app.get('/createProduct/:product_id', function (req, res) { l

我不熟悉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对象通过管道传输到请求调用。在这种情况下,您只需发出一个请求。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 call To中的url即可:

http://localhost:<port>/post_test
http://localhost:/post_test

记得换回来

这是什么?@JuhilSomaiya这是我应该作为post请求传递给目标API的Json。因此,只有包含产品详细信息的Json对象。更新问题以提高可读性。在调用此
https://somewebsite/api/products
?非常感谢!!我已经在谷歌上搜索了好几天,没有任何运气!!没问题!很乐意帮忙!如果我不想显示结果json,但想以html的形式处理和显示输出,我应该怎么做?我建议看一下,这允许您从对象生成html。在这种情况下,您可能不会通过管道传递API调用的结果,而是将其保存到对象并将其传递给res.render调用。