ExpressJs请求主体为空 [英] ExpressJs request body is empty

查看:76
本文介绍了ExpressJs请求主体为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 localhost:5000 有一个Express应用,在 localhost:3000 有一个react应用。

I have an express app at localhost:5000 and a react app at 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配合使用,但主体仍为空

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;


推荐答案

根据文档正文选项应该是一些特定类型之一,对象不能是其中之一。

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

尝试使用JSON字符串:

Try using a JSON string:

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

编辑:因为您是使用 no-cors ,您无法设置 Content-Type application / json 。相反,您需要生成一个URL编码的字符串,并将 Content-Type 设置为 application / x-www-form-urlencoded (因为 no-cors 仅适用于简单标头,如此处及其他)。

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

这篇关于ExpressJs请求主体为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆