Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
kurumkan Avatar asked Nov 29 '16 06:11

kurumkan


4 Answers

For people using Express>=4.16, bodyParser has been changed to the following:

app.use(express.json());
like image 182
darkvalance Avatar answered Nov 10 '22 07:11

darkvalance


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,
      });
like image 30
Michael Nelles Avatar answered Nov 10 '22 06:11

Michael Nelles


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}));
like image 21
QoP Avatar answered Nov 10 '22 07:11

QoP


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 */
like image 40
ali Atwa Avatar answered Nov 10 '22 05:11

ali Atwa