简体   繁体   中英

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

I am trying to use POST to send data from one rest service to another rest service.

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;

It returns empty object {}. Does anyone know how to send JSON body from one service to another service.

app.js

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

Your problem is likely not sending the request body, but reading it.

In order to process the body, you need to use a middleware. Generally you'll use bodyParser.json ( Docs , check bottom for examples)

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

app.use(bodyParser.json());

This will allow it to parse the JSON.

The other step is on the sending side ( first.js ). You'll need to add the header Content-Type: application/json .

Those two things will allow second.js to properly read the body and make it available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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