Axios Post Request Sending Undefined - node.js

I am having an issue with sending data from an Axios post request to my ExpressJS post route. When I try to read the data sent on the post route it shows as undefined. This is my Axios post:
axios.post('http://localhost:3000/temps/heating', {
messageType: 'heating',
toggle: 'on'
}).then(res => {
console.log(res);
}).catch(e => {
console.log(e)
})
and this is my ExpressJS Post route below. I have tried to use req.params req.body & req.messageType
routes.post('/heating', (req, res, next) => {
const messageType = req.data;
console.log(messageType);
})
I thought that because Axios is sending "data" I request data on the NodeJS post route?
Thanks

In your express app make sure to use body-parser: https://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser');
app.use(bodyParser.json());
In your route you should then be able to access req.body.messageType:
routes.post('/heating', (req, res, next) => {
const messageType = req.body.messageType;
console.log(messageType);
})

It looks like you are using express.js in your node app. If that's the case, it would be const messageType = req.body.messageType;

Related

react axios cros body empty

Working on my first MERN app. When I'm trying to call my backend api, it seems that the body content is lost. But it works correctly using Postman. So I guess I have something wrong with my CORS.
Bellow my Frontend and Backend code:
Frontend - login.jsx
import axios from 'axios';
...
axios.get(process.env.REACT_APP_API_URL+'/auth/login'
, {username: 'demo', password: '1234567'}
).then(user => {
console.log(user);
}).catch(error =>{
console.log(error);
});
Backend - index.js
const express = require('express');
const bodyParses = require('body-parser');
const cors = require('cors');
const authRoute = require('./routes/auth');
const app = express();
app.use(bodyParses.json());
app.use(bodyParses.urlencoded({ extended: true }));
app.use(cors());
app.use('/api/auth', authRoute);
...
Backend - auth.js
const rooter = require('express').Router();
rooter.get('/login', async (req, res) => {
console.log('*** req.body:', req.body);
...
}
I got this message in the browser console:
GET http://localhost:5000/api/auth/login 401 (Unauthorized) xhr.js:210
And on the backend side I got this
*** req.body: {}
Any help would be appreciated.
GET requests with axios don’t support a body, change it to a POST:
rooter.post('/login', async (req, res) => {
console.log('*** req.body:', req.body);
axios.post(process.env.REACT_APP_API_URL+'/auth/login'

Post request in express in not accepting request body

I tried everything to get my request body in POST method. I'm using postman with raw and form-data mode. Tried calling this API from react too nothing works. console.log(req.body) prints blank. {}
do let me know what I am missing.
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = 9000
const enableWs = require('express-ws');
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
console.log(req.body);
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
Now, I recreated your app, and it actually works.
I am using insomnia to test your api.
To the route "/" with Post, and some JSON.
Then in the Console.log I get the request body.
Console.log
Maybe you are testing incorrectly? Please get back to me if there is any question.
My guess is that you are not passing anything in your POST request, hence the empty body.
Be sure to specify Content-Type to application/json in postman's request headers.
In order for body-parser to parse req.body from JSON, your request must specify that the content is, in fact, JSON. Otherwise, it will not parse it; resulting in your blank req.body.
fetch('http://localhost:9000', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'hi',
}),
})

Using axios to execute a post request in nodejs but I am not able to receive data in the post route

I am trying to execute a post request using axios but the req.body is showing empty object . Here is my code :
const postData = {
tournamentId: tournamentId,
category: category,
contestantId: contestantId,
};
axios.post(`${process.env.URL}/joinTournament`, postData)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log("Body: ", res.data);
})
.catch((err) => {
console.error(err);
});
Try a few things like test your backend logic with Postman (An API Development Tool). Then try to console log your request in backend to confirm the request reaching is correct.
If all that checkout turn to your libraries if you are using expressjs try to use a middleware like body-parser and cors to send back responses
The Code being something like
For Cors
//Cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(69, function () {
console.log('CORS-enabled web server listening on port 80')
})
For Body-parser
//body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' })
Might as well setup a checker block where you'd check that if the request is missing some necessary info to send back some understandable response.
I have solved this issue using qs and calling stringify method on postData . Here is my solution :
const qs = require("qs");
const postData = {
tournamentId: tournamentId,
category: category,
contestantId: contestantId,
};
axios.post(`${process.env.URL}/joinTournament`, qs.stringify(postData))
.then((res) => {
console.log(`Status: ${res.status}`);
console.log("Body: ", res.data);
})
.catch((err) => {
console.error(err);
});
if your server works very well with request from postman and every things is Ok, you can do like this, without third party module

body undefined on axios post request

I have this endpoint on backend (node, express):
router.post('/createUser', (req, res, next) => {
try{
const { user } = req.body;
if(!user) next(createError(401))
data.push(user);
res.status(200).json(user)
} catch(e) {
next(e)
}
})
and this on front (service)
class EmployeeService {
constructor() {
this.api = axios.create({
baseURL: process.env.REACT_APP_BACK_DOMAIN || 'http://localhost:4000',
withCredentials: true
})
}
getPaginated = (page, size) => this.api.get(`/?page=${page}&size=${size}`).then(({data}) => data)
createUser = user => this.api.post('/createUser', user).then(({data}) => data)
}
When i receive createUser Request, i take body from req, but it is undefined, i console log "req" and this returned me an incoming message object Why? i need to receive body for push on array :(
the object that i create on front:
It seems to me that you are sending the user object wrong, Try this:
user = {id:1,name:"nombre"}
createUser = this.api.post('/createUser', user).then(({data}) => data)
And check if the body arrives to backEnd
This is let answer but...
As you mention you are receiving an object but not able to excess data though req.body
server API and Axios working fine then the problem is parser
try adding parser as shown below and make sure it is before app.use("/", router)
const express = require('express');
const app = express();
var router = express.Router();
// create application/x-www-form-urlencoded parser
app.use(express.urlencoded({ extended: false }));
// parse application/json
app.use(express.json());
app.use("/", router);
for more information check this
Express.js req.body undefined

req.body will not return a response

I've searched and tried other results, but none seem to render any results.
I'm trying to post data to the backend using postman as a test. The response is sending the 'success' message, but req.body returns an empty array every time I try. I'm using a node backend, with express and I'm trying to use routes. I've had success before, but for some reason I can't get it this time and my old code doesn't seem to work for this one. If I just log req, rather than req.body, I can see that the body is empty, the params are empty, but the url includes the params. I can post it, but it's rather long and I don't know if it's useful.
Here's the url I'm trying to hit: localhost:3000/?testParam=test&test=boop
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogTest', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
const postsRoute = require('./routes/post');
app.use(postsRoute);
module.exports = app;
post.js
const express = require('express');
const router = express.Router();
const postModel = require('../models/post'); //not using this yet
router.get("/", function(req, res){
console.log("Getting Posts...");
postModel.find({}, function(err, posts){
if(err){
res.send("{'status': 'error', 'response': "+err+"}");
}
else if(posts.length < 1){
res.send("{'status': 'null', 'response': {}}");
}
else{
res.send("{'status': 'success', 'response': "+posts+"}");
}
});
});
router.post("/", function(req, res){
console.log(req.body);
res.send('success');
});
module.exports = router;
I'm expecting the console to log {'testParam': 'test','test':'boop'}
also, I've tried parsing req.body as json and stringifying it, but it causes the server to crash.
I think you are confused about http methods and how they work.
req.body is the POST request body, it is the data passed by the client when he sends a POST request to your api endpoint. If you are not sending any data in your POST request, then req.body will be empty.
In your example, to get the data from a request like localhost:3000/?testParam=test&test=boop you would need to look in req.params instead of req.body.
You need to try accessing the params variable of the request by code, trying to go through a log to find params might not be accurate therefore try
router.post("/", function(req, res){
console.log(req.params);
res.send('success');
});

Resources