Req.body is empty node.js and express

柔情痞子 提交于 2021-02-10 14:14:12

问题


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);

回答1:


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);



回答2:


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 }));



回答3:


Add this two line to your code

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


来源:https://stackoverflow.com/questions/55565442/req-body-is-empty-node-js-and-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!