ExpressJs request body is empty

余生颓废 提交于 2019-12-13 03:56:16

问题


I have an express app at localhost:5000 and a react app at localhost:3000.

I am calling it via

            fetch(`${backendUrl}/charge`, {
                method: "POST",
                mode: "no-cors",
                headers: {
                    "Content-Type": "application/json"
                },
                body: {
                    stripeToken: token,
                    chargeAmount: this.state.donationAmount
                }
            })

And responding with

function route(req, res) {
  console.log(req.body);
}

Server should be properly configured to work with CORS, but the body is still empty.

//configure env variables
require("dotenv").config();

//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");

//import route functions
const StripeRoute = require("./StripeRoute");

//setup app
const app = express();
const port = process.env.PORT || 5000;

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

//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes

//Connect functions to API routes
app.post("/charge", StripeRoute);

module.exports = app;

回答1:


According to the documentation, the body option should be one of a few specific types, Object not being one of them.

Try using a JSON string:

body: JSON.stringify({
  stripeToken: token,
  chargeAmount: this.state.donationAmount
})

EDIT: because you're using no-cors, you can't set Content-Type application/json. Instead, you need to generate a URL-encoded string and set Content-Type to application/x-www-form-urlencoded (because no-cors will only work using "simple headers", as explained here and further).



来源:https://stackoverflow.com/questions/53214229/expressjs-request-body-is-empty

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