Reputation: 79
my browser side js code:
import axios from 'axios';
var testObject = {
field : 'this is a test field'
}
axios.post('/create', testObject)
.then((res) => {
console.log(res);
});
my nodejs code:
const express = require('express');
const path = require('path');
const app = express();
//middlewares
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.resolve(__dirname, '../dist')));
app.post('/create', (req, res) => {
console.log(req.body);
res.send('this is the server response');
});
const port = 3000;
app.listen(port, () => {
console.log('server listening on port ' + port);
});
my node js output:
server listening on port 3000
{}
my browser console output:
{data: "this is the server response", status: 200, statusText: "OK", headers: {…}, config:
{…}, …}
please look that I'm alredy using a parser body middleware, the request is working fine but for some reason the server cant get the request body.
Upvotes: -1
Views: 6953
Reputation: 339
Make sure to use body-parser for Express. In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script. If not:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
npm install body-parser --save
now get body
of your request in nodejs
app.post('/create', (req, res, next) => {
console.log(req.body);
});
Upvotes: 1
Reputation: 6830
You have to use app.use(express.json())
// parse application/json
server.use(express.json());
app.post('/create', (req, res) => {
console.log(req.body);
res.send('this is the server response');
});
You also have to update your ajax request with following:
contentType: "application/json",
data: JSON.stringify(hellodata),
Upvotes: 3