axios post request.body 是空对象

Axios post request.body is empty object

我正在尝试 post 来自我的反应的数据。后端 - 快递。 这是后端代码:

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var  methodOverride = require("method-override");
var mongoose = require("mongoose");
var expressSanitizer = require("express-sanitizer");

mongoose.connect("mongodb://localhost/blog-react");

//app config
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
//must be after parser
app.use(expressSanitizer());
app.use(methodOverride("_method"));

//schema config
var blogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    //it should be date. With default value now.
    created: {
        type: Date, default: Date.now
    }
});

var Blog = mongoose.model("Blog", blogSchema);


function handle500(response, error){
    console.log(error.stack);
    response.status(500);
    response.json({error: "error: internal server error"});     
}

app.post("/api/blogs", function(request, response){         
    var blog = {
        title: request.sanitize(request.body.title),
        image: request.sanitize(request.body.image),
        body: request.sanitize(request.body.body)
    };
    console.log(request.body);
    Blog.create(blog, function(error, newBlog){
        if(error){
            console.log("inside post handler ERROR")
            handle500(response, error);
        }
        else{
            console.log("inside post handler OK")
            response.json({status: "success"});         
        }
    }); 
});

反应代码:

    var requestUrl = "/api/blogs";      
    var blog = {
        title: "a",
        image: "b",
        body: "c"
    }   
    axios.post(requestUrl, blog)
    .then(function(response){
        console.log("success",response.data)
    })
    .catch(function(response){
        console.log("error", response);
    }); 

当我通过 axios post 数据时 - request.body 总是 {} 但是如果我通过常规形式 post 数据 - 一切都是正确的 - request.body 包含所有预期数据。

我对 axios 做错了什么?

您缺少一个中间件,bodyParser.json()。将其添加到您的配置中。

mongoose.connect("mongodb://localhost/blog-react");

app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: true}));

看起来你只剩下两点可以让它工作了:

一:http方法应该设置为POST而不是GET,因为你想发送一些东西。

二:然后您可以添加 http header(就像您使用授权所做的那样 header)Content-Type: 'application/json`

在 back-end 上,不要忘记使用某种 body 解析器实用程序包,例如:body-parser 并使用您的应用程序进行设置。

我想你的服务器正在使用 express,下面是你将如何使用 express:

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json();

app.use(jsonParser); // use it globally
app.get('your_route', jsonParser, otherMiddleware, (req, res) => ...); // use it for specific routes

/* ... rest of your code */

对我来说,问题是有效的 JSON 格式,包括变量上的双引号。

这个没有工作

      const res = await axios.post(serverPath + "/user/login", {
         email: email,
         password: password,
      });

DID 有效(电子邮件和密码用双引号引起来)

      const res = await axios.post(serverPath + "/user/login", {
         "email": email,
         "password": password,
      });

对于使用 Express>=4.16 的人,bodyParser 已更改为以下内容:

app.use(express.json());