简体   繁体   中英

Axios post request.body is empty object

I am trying to post data from my react. Backend - express. Here is backend code:

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"});         
        }
    }); 
});

React code:

    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);
    }); 

When I post data via axios - request.body is always {} But if I post data via regular form - all is correct - request.body contains all expected data.

What am I doing wrong with axios?

You are missing one middleware, bodyParser.json() . Add it to your configuration.

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}));

It looks like you only have two points left to make it work :

one : the http method should be set to POST instead of GET since you want to send something.

two : you can then add the http header (like what you did with the authorization header) Content-Type: 'application/json`

On the back-end don't forget to use some kind of body parser utility package like this one : body-parser and set it up with your app.

I suppose your server is using express, here is how you will do it with 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 */

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

app.use(express.json());

For me the issue was valid JSON format including double quotes on the variables.

This did not work

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

This DID work (with double quotes around email and password)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM