How to retrieve form-data sent from postman in express? - node.js

I successfully retrieved data in node when it was x-www-form-urlencoded or raw.
app.use(express.json());
app.use(express.urlencoded());
app.post("/api/posttest", (req, res) => {
console.log(req.body);
res.send("POST data received");
});
But when I use form-data, the req.body is empty and I didn't find my data anywhere else in req. Can this be retrieved with express without additional modules?

I believe you need the express.js middleware 'body-parser' in order to retrieve/see req.body.
Body parser used to be part of express.js but has since been removed.

Related

Postman send strange response for raw JSON post (node js)

I'm trying to do a POST request using raw json.
In the Body tab I have "raw" selected with this body:
{
"name": "book"
}
On the Node js side I'm doing res.send(JSON.stringify(req.body))
router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}
And in POSTMAN response I receive:
{"{\n\"name\": \"book\"\n}":""}
When expected something like
{"name":"book"}
Have no idea - where could be a reason for it?
You'll need to use the Express JSON body parser, install using
npm install body-parser;
Then:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.
Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")
Here's a simple express app that will echo any JSON POST:
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
If you're on Express v4.16.0 onwards, try to add this line before app.listen():
app.use(express.json());
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?
Can you log the response type from the server to console to check whether its already json content or not?
try with hard coded json response and then with dynamic variable
res.json({"name":"book"});

nodeJS Express: express.urlencoded() empty req.body

I have an API that works as expected from all incoming requests using application/json request. But recently I encounter the need to process a POST request from x-www-form-urlencoded and the body of the request is always empty.
I test the API using POSTMAN and works great when I send the request using the option raw with JSON(application/json). But when send data using x-www-form-urlencoded the body is empty.
The route for the POST is app/api/sensor, and the files are the following:
app.js
var express = require('express');
var app = express();
.......
app.use(express.json());
app.use(express.urlencoded()); // THIS SHOULD WORK!
......
sensor.js POST
......
sensorRoute.post('/', (req, res, next) => {
console.log(req.body);
const temperature = req.body.temperature;
console.log(temperature);
if (!temperature) {
return res.status(400).send({'res': 'Missing data'});
} else {
return res.status(200).send({'res': 'OK'});
}
});
....
The expected result should show the data that is been send using postman in the req.body and not an empty object, and work the same as the application/jason.
change
app.use(express.urlencoded());
to
app.use(bodyParser.urlencoded({
extended: true
}));
The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.
Defaults to true, but using the default has been deprecated. so add the option extended: true

How can I replace a collection with PUT using express?

I'm trying to take a json collection of data and send it with postman or Advanced REST Client. The biggest thing I'm getting stuck with with is where the data is. I can't seem to find it in any part of the request. Note this must be done using express.
app.put('/api/', function (req, res) {
//Get data and replace table in database
res.send("RECEIVED");
});
You can use body-parser to parse the request and provide you all that submited data through request.body.data if you send you data as a form-data or request.params.data if you send your data as a query parameter.
npm install body-parser --save
And import it and use it as a middleware
var bodyParser = require("body-parser");
// some other code goes here like
// var express = require("express"):
// var app = express()
// and here attach the body-parser middleware like thiss
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
when you make a request with any Advanced REST client each key in the JSON that you pass to the request body will be accessible as request.body.key you can learn more about body-parser body-parser doc

NodeJS req.body is always empty

My server.js code:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
const AboutController = require('./controllers/AboutController');
app.use('/about', AboutController);
AboutController.js
router.post('/store', (req, res, next) => {
// GETTING REQUEST DETAILS AND INITIALIZATION
let content = req.body.content;
let company_name = req.body.company_name;
console.log(req.body);
});
module.exports = router;
Problem
req.body always return {} which is empty object and I don't know why!
What I have tried
I have tried to console.log(req) and it returned objects but still the body object is empty!
Client Side Request
I am using Postman form-data to simulate client request.
The reason your Postman request didn't work is because you aren't parsing a form-data type anywhere in your app. The only middleware that you have for parsing is bodyParser.json(), which as it says on the tin, parses JSON. For example, if you wanted to parse x-www-form-urlencoded, you could use bodyParser.urlencoded().
If you want what you currently have to work, you need to send it JSON, not form-data
Regardless, the form-data type is normally used for larger payloads (ex: files)
I found the solution..
I was using Postman and I was using form-data instead of raw and json and it worked fine I don't know why yet!

Nodejs: How can i simply get the request body using express4?

Now that express is not shipped anymore with middleware that fills the req.body variable i am fighting to get req.body filled again.
I am sending a POST request to /xyz/:object/feedback.
here my code:
app.post('/xyz/:object/feedback', function(req, res)
{
console.log('Feedback received.');
console.log('Body: ', req.body); // is not available :(
res.set('Content-Type', 'text/plain; charset=utf8');
res.send(result ? JSON.stringify(req.body) : err);
});
I tried to use body-parser already, but "Feedback received." never got logged to my console. So something seems to get stuck here:
var bodyParser = require('body-parser');
app.use(bodyParser);
How can i get req.body filled? (i need some working code)
The problem is that you pass the whole module to the use method not the required instance.
Instead of this:
app.use(bodyParser);
do
app.use(bodyParser());
You need to do app.use(bodyParser()).
bodyParser() will return a function with what to use. bodyParser on its own is an invalid function for Express.

Resources