繁体   English   中英

如何在请求中添加正文并在Node.js Express中获得第二个Rest服务

[英]How to add body in the request and get in second rest service in nodejs express

我正在尝试使用POST将数据从一个Rest服务发送到另一个Rest服务。

first.js

const express = require("express");
const http = require("http");

var router = express.Router();

var options = {
  host: "localhost",
  port: "3000",
  path: "/second",
  method: "POST",
  body: JSON.stringify({ foo: "foo" })
};

router.get("/", function(req, res, next) {
  http.request(options);
});

module.exports = router;

second.js

var express = require("express");
var router = express.Router();

router.post("/", function(req, res, next) {
  console.log(req.body);
  res.send("Hello");
});

module.exports = router;

它返回空对象{}。 有谁知道如何将JSON正文从一个服务发送到另一服务。

app.js

app.use("/first", first);
app.use("/second", second);

您的问题可能不是发送请求正文,而是阅读请求正文。

为了处理身体,您需要使用中间件。 通常,您将使用bodyParser.jsonDocs ,请查看底部的示例)

// In second.js, in addition to your other stuff
import bodyParser from 'body-parser';

app.use(bodyParser.json());

这将允许它解析JSON。

另一步骤是在发送方( first.js )。 您需要添加标题Content-Type: application/json

这两件事将使second.js能够正确读取正文并使之可用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM