简体   繁体   中英

Req.body is empty node.js and express

I am trying to send a string from a client side page to a server, but the server receives an empty object. Here is my client side code:

fetch("/sugestions/sugestions.txt", {
  method: "POST",
  body: JSON.stringify({ info: "Some data" }),
  headers: {
    "Content-Type": "application/json; charset=utf-8"
  }
})
  .then(res => {
    if (res.ok) console.log("Yay it worked!");
    else window.alert("Uh oh. Something went wrong!\n" + res);
  });

This is my server side code:

const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");

const app = express();
const port = process.env.PORT || 8080;

app.set("view engine", "ejs");
app.use(bodyParser());

app.post("/sugestions/*", (req, res) => {
  info = JSON.parse(req.body);
  fs.appendFile(path("req").pathname, info.info, (err) => {
    if (err) res.status(404).end();
    else res.status(200).end();
  });
});

app.listen(port);

Here is the path function, in case that matters:

const path = req => url.parse(`${req.protocol}://${req.get("host")}${req.originalUrl}`, true);

To access the body of a request you need to use bodyParser. And you need to explicitly tell your bodyParser about the data formats that you need to parse. Now coming to your solution, Replace

app.use(bodyParser());

with

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Add this two line to your code

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Since express 4.16.0 you can use app.use(express.json()); to get the json data from request,in your case it would be.You don't require to use bodyparser and all.

const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");

const app = express();
const port = process.env.PORT || 8080;

app.set("view engine", "ejs");
app.use(express.json())// add this line

app.post("/sugestions/*", (req, res) => {
  info = JSON.parse(req.body);
  fs.appendFile(path("req").pathname, info.info, (err) => {
    if (err) res.status(404).end();
    else res.status(200).end();
  });
});

app.listen(port);

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