【问题标题】:Axios post request.body is empty objectAxios post request.body 是空对象
【发布时间】:2017-04-13 01:27:13
【问题描述】:

我正在尝试从我的反应中发布数据。后端 - 快递。 这是后端代码:

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 发布数据时,request.body 始终为 {} 但是如果我通过常规形式发布数据 - 一切都是正确的 - request.body 包含所有预期的数据。

我在 axios 上做错了什么?

【问题讨论】:

  • 检查您的浏览器的开发工具(网络选项卡)以查看发送到您的服务器的确切内容

标签: node.js express reactjs axios


【解决方案1】:

您缺少一个中间件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}));

【讨论】:

  • 我登录只是为了感谢您。我在使用 bodyParser.urlencoded 时不知道它与 bodyParser.json() 选项完全不同。
【解决方案2】:

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

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

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

在后端不要忘记使用某种 body parser 实用程序包,例如: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 */

【讨论】:

    【解决方案3】:

    对我来说,问题是有效的 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,
          });
    

    【讨论】:

    • 两者都一样
    • 第二个变量名在:左侧有双引号
    • 两者在声明对象键时使用引号不会改变与对象有关的任何内容方面是相同的。除非您想使用不是有效 JavaScript 标识符的键,否则引号不会产生影响。
    • JSON 对象与 Javascript 对象的不同之处在于变量名 must 用双引号括起来 json-schema.org/understanding-json-schema/reference/object.html
    • 我同意谢谢。这从来不是我的原意。我发表这篇文章的目的是希望为那些可能需要更改对象格式的人节省时间,以防万一这是错误因素。在我的特殊情况下,接收到的对象必须以这种格式完成。
    【解决方案4】:

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

    app.use(express.json());
    

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 2017-02-28
      • 2021-07-27
      • 1970-01-01
      • 2015-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2017-04-07
      相关资源
      最近更新 更多