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());
Related
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());
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}`);
})
I am trying to get data sent by postman row->text data but fail to get.
I am able to print complete body but how do i print body param?
body is in the form of query string.
NodeCode:
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.post('/data/UploadLogsToServer', async (req, res) => {
return res.json(req.body);
});
above code prints complete body like
But How do i fetch only Store parameter from query string ?
querystring npm module resolved my problem
Solution:
var querystring = require('querystring');
app.post('/data/UploadLogsToServer', async (req, res) => {
var q = querystring.parse(req.body);
return res.json(q.Store);
});
I'm trying to extract POST data using a NodeJS script (with Express). The body is received, but I cannot seem to extract the variable from it when posting to the page with Postman. The variable is undefined, although I have used the same code I found in different questions. I have correctly installed Nodejs, express and body-parser.
To clarify, I'm posting form-data with Postman with key 'username' and value 'test'.
Anyone knows what I'm doing wrong?
var https = require('https');
var fs = require('fs');
var app = require('express')();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var httpsOptions = {
key: fs.readFileSync('/home/privkey.pem'),
cert: fs.readFileSync('/home/cert.pem'),
};
var server = https.createServer(httpsOptions, app);
server.listen(3000);
app.get('/', function(req, res) { //On get
res.send(req.method);
});
app.post('/', function(req, res) { //On post
res.send( req.body.username );
});
I guess it has to do with the encoding:
JSON:
you have to set a header with Content-Type: application/json and
add the encoding in express before the route :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Otherwise you can just use the option x-www-form-urlencoded and set the inputs
This is the code of my server :
var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());
app.post("/", function(req, res) {
res.send(req.body);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".
However I keep getting an empty object in the response. The req.body property is always empty.
Did I miss something?
Add the encoding of the request. Here is an example
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..
Then select x-www-form-urlencoded in Postman or set Content-Type to application/json and select raw
Edit for use of raw
Raw
{
"foo": "bar"
}
Headers
Content-Type: application/json
EDIT #2 Answering questions from chat:
why it can't work with form-data?
You sure can, just look at this answer How to handle FormData from express 4
What is the difference between using x-www-form-urlencoded and raw
differences in application/json and application/x-www-form-urlencoded
let express = require('express');
let app = express();
// For POST-Support
let bodyParser = require('body-parser');
let multer = require('multer');
let upload = multer();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/api/sayHello', upload.array(), (request, response) => {
let a = request.body.a;
let b = request.body.b;
let c = parseInt(a) + parseInt(b);
response.send('Result : '+c);
console.log('Result : '+c);
});
app.listen(3000);
Sample JSON and result of the JSON:
Set Content-typeL application/JSON:
I encountered this problem while using routers. Only GET was working, POST, PATCH and delete was reflecting "undefined" for req.body. After using the body-parser in the router files, I was able to get all the HTTP methods working...
Here is how I did it:
...
const bodyParser = require('body-parser')
...
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
...
...
// for post
router.post('/users', async (req, res) => {
const user = await new User(req.body) // here is where I was getting req.body as undefined before using body-parser
user.save().then(() => {
res.status(201).send(user)
}).catch((error) => {
res.status(400).send(error)
})
})
For PATCH and DELETE as well, this trick suggested by user568109 worked.
On more point I want to add is if you created your project through Express.js generator
in your app.js it also generates bellow code
app.use(express.json());
if you put your body-parser above this code the req.body will return null or undefined
you should put it bellow the above code see bellow for correct placement
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
I experienced the same issue. I tried all that had been suggested here. I decided to console log the value of the request object. It's a huge object. Inside this object I saw this query object carrying my post data:
query: {
title: 'API',
content: 'API stands for Application Programming Interface.'
}
So it turns out that request.query, and not request.body, contains the values I send along with my post request from Postman.