axios post request from frontend not recieving in node js backend - node.js

I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?

By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().

You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());

We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());

Related

POST request returns undefined

When the request from postman initiated with the json as given below, I get hello undefined as response.
request json
{
"name":"test"
}
my middleware
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.get('/hello', (req, res)=>{
return res.send("hello");
});
app.post('/hello', (req, res)=>{
console.log(req.body);
return res.send(`hello ${req.body.name}`);
})
app.listen(8000, () => console.log('listening on port 8000'));
started the server with following command
npx babel-node src/server.js
Since express 4.16.0 you can use app.use(express.json()); to get the json data from request,in your case it would be.You don't require to use bodyparser and all.
const app = express();
app.use(bodyParser.json()); // remove this
app.use(express.json())// add this line
Actually issue is not with the code. The Postman client making the request didn't mark it as application/json type request. Once I rectified it, it just worked as expected.
use bodyParser as meddleware
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); //add this
app.use(bodyParser.json());
also
app.post('/hello', (req, res)=>{
console.log(req.body);
name.push(req.body.name) // add this if you store in array
return res.send(`hello ${req.body.name}`);
})

NodeJs unable catch the data post from ReactJs form

I using ReactJs build the form for user key in the details. I also using NodeJs to handle the post data from the React. But the NodeJs seem like did not catched the data.
This is react event handling
handleSave(e){
let caseData=this.state.caseInfo
let url = 'http://localhost:8080'
console.log(caseData)
fetch(url,{
method:"POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify({caseInfo: caseData}),
})
}
This is NodeJS
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser')
var express = require('express')
var app = express()
http.createServer(function(req,res){
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(function (req, res){
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
console.log(JSON.stringify(req.body));
})
}).listen(8080);
I expect the data from the React can using post method to the Node and display the data in console log. However in the console of the server it display nothing.
It seems like you're not using express in the standard way. I'd change it to be more like the following...
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);
And probably just get rid of the call to http.createServer altogether.
--
Check out the docs for more routing examples: https://expressjs.com/en/starter/basic-routing.html
If you are serving your react app from another server, for instance localhost:3000 (as used by create react app), and you are trying to make api calls to a server on localhost:8080 you are going to get CORS errors because the browser sees these as two different domains. To get started, you can look at the docs here: https://expressjs.com/en/resources/middleware/cors.html
But you will probably have to npm install cors where your server lives and use something like the following:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);

How to get API post request with json data

I'm triyng to make an API request using postman and body raw data, but I can't read the data on server side.
My request:
http://prntscr.com/n38hes
http://prntscr.com/n38hq9
I've already tried:
app.post('/test', function (req, res) {
console.log(req.query)
})
and:
app.post('/test', function (req, res) {
console.log(req.body)
})
but both of them prints {}
I would like to obtain the username and the password for the request I made using postman.
Make sure you have body parser configured.
var bodyParser = require('body-parser');
//here app is express app
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());

Strange Response from express server

I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation

BodyParser data is undefined after AJAX call

The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()

Resources