Node JS POST request returning undefined body - javascript

Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.
I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.
I have added body-parse as suggested but still no joy.
I will post my server code and request below.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.post('/api/save-json', (req, res) => {
console.log(req);
res.send(
`I received your POST request. This is what you sent me: ${req.body.json}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
My postman request is:
{
"body" :
{
"json": "some data"
}
}
Any ideas?

body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json

Related

How to get file data and other form data sent in POST request in Node Js

I am sending form data values using Postman as given here. Postman Request.
I am making use of NodeJS server in the backend to get the data from this POST request.
The code for my app.js file is given below.
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(bodyParser.json({
limit: '50mb',
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
const { multerUploadOneFile } = require(path.resolve(__dirname, 'helpers', 'multerConfig'));
app.post('/upload', function (req, res) {
// **Here I need to get the other parameters in the request body, i.e ```userId```, ```fileType```
console.log(req.body);
multerUploadOneFile(req, res, function (error) {
if (error) {
return res.status(401).send({
status: 'failure',
message: error.message
});
}
return res.status(200).send({
status: 'success',
message: 'successfully uploaded file.',
});
})
});
I am logging the request body in /upload api endpoint but I am not able to get anything. Please let me know how can I get the req.body in callback of /upload api endpoint.
body-parser doesn't support multi-part bodies.
multer (which you're correctly using) does, however it needs to execute and parse the request before you'll be able to access anything.
multerUploadOneFile needs to execute before you have acceess to .body or .file.
app.post('/upload', function (req, res) {
multerUploadOneFile(req, res, function (error) {
console.log(req.body, req.file);

Node.js req.body undefined in form-data content-type

Here I have created the small demo for this form-data passing API. Now I'm checking this API using postman but I'm not getting any data.
Code
const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.json({
limit: "50mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true
})
);
app.post('/form-data', (req, res) => {
console.log("form-data ->> ", req.body)
});
server = http.createServer(app);
server.listen(4000[![enter image description here][1]][1], () => {
console.log(`Server started`);
});
Server log
Server started
form-data ->> {}
Header
I tried to reproduce your code with small changes.
const express = require("express");
const bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();
const app = express();
// for parsing application/json
app.use(
bodyParser.json({
limit: "50mb",
})
);
// for parsing application/xwww-form-urlencoded
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true,
})
);
// for parsing multipart/form-data
app.use(upload.array());
app.post("/form-data", (req, res) => {
console.log(`\nform-data ->> ${JSON.stringify(req.body)}`);
res.send(req.body);
});
const port = 3000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
I removed your server initialization since we can use app listen directly from the expressjs.
And I can send post with "form-data", "x-www-form-urlencoded", or "raw" successfully.
You might double-check on which tutorial you following. Since express documentation is clear enough.
*Edited
I added multer to parsing the form-data.
if you are using multer as middleware on the post route with other middle middlewares put the multer middleware first.
app.post(
"/api/private/buyer/add-buyer",
[
upload, verifySignUp.checkDuplicateUsernameOrEmail,
],
controller.createBuyer
);
here upload is multer middleware I put it first it works for me.

Node.js express - body of POST request is always empty

I am trying to read the body of POST request using Express in Node.JS framework. I send a HTTP POST request using HTML form. I detected a POST request on WireShark with the following data:
This shows that the request is sent successfully. I expected JSON format, which is the one that Express successfully parsed for me, but this format just doesn't seem to work no matter what I tried. My current implementation goes like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var jsonParser = bodyParser.json()
//Import static files
app.use(express.static('../public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', jsonParser, (req, res) => {
console.log(req.body);
res.send(200);
});
app.listen(port, () => console.log("Server started"));
No matter what I try from other posts, it still does not seem to return me any data.
Does anyone have an idea how to fix this problem?
Why to you use 'jsonParser' in the app route? Try something like:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/post-test', (req, res) => {
console.log('Got body:', req.body);
res.sendStatus(200);
});

Node, how can I send response headers on a node/express app?

I have a basic server. One of my tests that I need to pass is to send the response header of 200. I added the code for the server as it is now. But not sure how to send response headers. Thanks for any help you may be able to provide!
var express = require('express');
var bodyParser = require('body-parser');
var Users = require('./models/users');
var app = express();
app.use(bodyParser.json());
// YOUR CODE BELOW
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
// middleware for all requests:
router.use(function(req, res, next){
console.log('we out here babay!');
// get to the next route and ensures we don't stop here.
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.use('/api', router);
// Do not touch this invocation of the `listen` method
app.listen('8888', function () {
console.log('listening on 8888');
});
// Do not touch the exports object
module.exports = app;
Use res.status(CODE) method!
res.status(200).json({ message: 'hooray! welcome to our api!' });
As highlighted in comments by jfriend00, default status code is 200 so any regular response will already be 200 but for other codes like 500 or 404, if your client side is considering it while reading the response, you can use res.status() method.

Unable to parse url encoded data in express

I have this super simple server:
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/update', (req, resp) => {
debugger;
resp.send();
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Using postman, I am sending data to the server like this:
REPL shows me an empty body when the request is received:
> req.body
{}
I would expect the body to look something like this:
{
"hello": "world"
}
Am I missing something obvious ? Probably ..
By choosing x-form-urlencoded below postman will send the Content-Type header for you, you dont need to specify it again yourself. You can see this by clicking the Preview button. So you're sending a duplicate Content-Type header which seems to trip up body parser.

Categories