node.js - 使用 Express 传递 json 正文调用现有 API

标签 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) {
        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/

相关文章:

javascript - 无法解决我的 Express 应用中的 CORS 政策

node.js - 通过连接几个表获取不同的数据 Sequelize ORM

node.js - 开 Jest : child_process. exec.mockImplementation 不是一个函数

spring - 了解 RESTful Web 服务压力测试结果

web-services - SOAP 的末日即将来临吗?

node.js - CORS 错误,但仅在 POST 请求时出现,尽管有 cors 配置(GET 没有问题)

javascript - 如何在 Mongoose 中找到 "By Name"

javascript - 如何在 React Native 中使用 axios 将图像上传到服务器?

node.js - 将 youtube-dl 脚本上传到 Google Cloud 存储

java - jUnit 问题 - Restful Web 服务的集成测试