首页 > 解决方案 > ExpressJs 请求正文为空

问题描述

我有一个快速应用程序localhost:5000和一个反应应用程序localhost:3000

我通过调用它

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

并回应

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

服务器应正确配置为使用 CORS,但正文仍然是空的。

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

标签: node.jsexpresscorsfetch

解决方案


根据文档,该body选项应该是几种特定类型之一,Object而不是其中之一。

尝试使用 JSON 字符串:

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

编辑:因为你正在使用no-cors,你不能设置Content-Type application/json。相反,您需要生成一个 URL 编码的字符串并设置Content-Typeapplication/x-www-form-urlencoded(因为no-cors只能使用“简单标头”,如此和进一步解释)。


推荐阅读