PUT/PATCH merhtod return Undefind and {} object , when use the with form-data in nodejs,expressJs - node.js

I'm stuck for the last two days. I have tried all the solutions for it but still, I'm getting undefined or {} object when running the method with PUT and PATCH in nodejs
Postman screen shot is here
index.js
[const express = require("express")
const cors = require("cors")
const bodyParser = require("body-parser")
require("./db/db.config")
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const PORT = 8000
const Customer = require("./routes/customerRoutes")
app.use(cors())
app.use(Customer)
app.listen(PORT, () => {
console.log("Server is running on", PORT)
})][1]
package.json
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"moment": "^2.29.4",
"mongoose": "^6.9.2",
"multer": "*",
"validator": "^13.9.0"
},

Your Postman request is set to form-data which means a content-type of multipart/form-data and you don't have any Express middleware to read/parse that content-type.
Change postman to either x-www-form-urlencoded or json to match the middleware you do have or you will have to install middleware that can handle multipart/form-data. Usually, you would not use multipart/form-data unless you were uploading file data along with your form data since that's why multi-part is used (multiple parts to the upload).
In the Postman example you show a screenshot of, the content-type of x-www-form-urlencoded should work just fine and your app.use(bodyParser.urlencoded({ extended: true })) middleware will handle it and that's what a standard HTML form upload would typically be.

Related

req.body returns an empty object eventhough data is passed through form

this is my index.js code and it returns an empty object even though data is passed on from the front-end
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());
app.use(express.json());
app.post("/api/register", (req, res) => {
console.log(req.body);
res.json({ status: "ok" });
});
app.listen(8000, () => {
console.log("listening on port 8000 . . . ");
});
For the specific case you're talking about, you usually need oa body parser to be able to access the form input fields. The minimum example that I advice you to build above it is the following:
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
Some other hints
Make sure that the request is being submitted with the header Content-Type: application/x-www-form-urlencoded or Content-Type: application/json
Check if there any CORS problems
Here's More reference for you
The main reason this does not work is
some how the data passed in body is in text format while req.body is
expecting json data
make sure to double chek the 'Content-Type':'application/json' is set on the request headers
if you are using multipart/form-data or require a file upload from frontend you will need a multer as middleware for your post/patch requests, otherwise you can set your frontend to send application/json
[edit]
this line looks missing from your index.js
app.use(express.urlencoded({extended: true}))

How to use body request express

I want to access to the body to my request but he is empty. I use a body-Parser but I don't know why I haven't data in my body.
import express from 'express';
import * as bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const port = 3000;
app.post('/', (request, response) => {
response.send(request.body);
});
app.listen(port, () => {
console.log(`you can run the server on http://localhost:${ port }`);
});
result:
{}
for my request I use postman
so I don't understand, I read other topic or forums and he this is the same code.
body-parser uses the Content-Type header to determine how the body will be parsed. My immediate suspicion (because I've done the same thing before) is that you may not be passing the Content-Type header - for example, if you are trying to use JSON, you need to be sending Content-Type: application/json on your POST request.

Difficulty doing an express upgrade to 4.x

After following the express 3 to 4 migration guide, I get nothing but timeouts from my app. Silence, nothing in log output, just timeouts, leaving me no idea how to debug.
I am hoping somebody can see the mistake I made in the following. Here's a before and after on my server and package files. After changing package.json, I did npm install, and have started and restarted node.
package.js before...
"express": "~3.3.5",
server.js before...
var express = require('express');
var app = express();
app.use(passport.initialize());
app.use(express.static('./public'));
app.use(express.compress());
app.use(express.methodOverride());
app.use(express.bodyParser());
package.js after...
"express": "*",
"serve-static": "*",
"compression": "*",
"method-override": "*",
"body-parser": "*",
server.js after...
var express = require('express');
var app = express();
app.use(passport.initialize());
var serveStatic = require('serve-static');
var compression = require('compression');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
app.use(serveStatic('./public'));
app.use(compression);
app.use(methodOverride);
app.use(bodyParser);
I hope I am presenting the relevant bits here. I am a little lost, with no errors to follow.
One issue is that you need to execute the middleware-generating function and pass their return values to .use() instead of the middleware-generating function itself. Examples:
app.use(compression());
app.use(methodOverride());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Any optional parameters for each middleware will depend on your needs of course, so you will want to consult the modules' documentation.

Node get posted variables via body-parser

I'm trying to retrieve the posted variables in a node application. I'm using Postman form-data (like I have in so many other API testing situations) to post a message to my node application. But when I console.log the request.body, I get an empty object. Here is my entire node app:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/foo',function(request,response){
console.log(request.body);
});
app.listen(3000, function(){
console.log('listening on *:3000');
});
After posting some data, here is what shows in my console:
listening on *:3000
{}
Here is my package.json:
{
"name": "api",
"version": "0.0.1",
"description": "api",
"dependencies": {
"express": "^4.12.4",
"socket.io": "^1.3.5",
"body-parser": "~1.12.0"
}
}
I think I'd like to continue to use body parser because I plan on making this an API with json data. The app loads up just fine with no errors. What am I missing?
After some tests, I found out that body-parser is not able to parse multipart/form-data as they state on their README, which is the default encoding on Postman.
To parse this format, you can use: (from their README, again)
busboy and
connect-busboy
multiparty and
connect-multiparty
formidable
multer
If it's just for debugging purpose, set Postman to send either:
x-www-form-encoded by checking the appropriate checkbox (see picture)
Or raw mode, being careful to set the mime header to application/json or the parser will ignore it (see picture)
I am getting expected console outputs when I post data using postman and your code when setting the content-type to application/x-www-form-urlencoded. npm-bodyparser does not handle multipart/form-data, which is what you were posting.
To parse multipart/form-data, use multer or busboy.

Express.js req.body undefined

I have this as configuration of my Express server
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
But still when I ask for req.body.something in my routes I get some error pointing out that body is undefined. Here is an example of a route that uses req.body :
app.post('/admin', function(req, res){
console.log(req.body.name);
});
I read that this problem is caused by the lack of app.use(express.bodyParser()); but as you can see I call it before the routes.
Any clue?
UPDATE July 2020
express.bodyParser() is no longer bundled as part of express. You need to install it separately before loading:
npm i body-parser
// then in your app
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
See here for further info
original follows
You must make sure that you define all configurations BEFORE defining routes. If you do so, you can continue to use express.bodyParser().
An example is as follows:
var express = require('express'),
app = express(),
port = parseInt(process.env.PORT, 10) || 8080;
app.configure(function(){
app.use(express.bodyParser());
});
app.listen(port);
app.post("/someRoute", function(req, res) {
console.log(req.body);
res.send({ status: 'SUCCESS' });
});
Latest versions of Express (4.x) has unbundled the middleware from the core framework. If you need body parser, you need to install it separately
npm install body-parser --save
and then do this in your code
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Express 4, has built-in body parser. No need to install separate body-parser. So below will work:
export const app = express();
app.use(express.json());
No. You need to use app.use(express.bodyParser()) before app.use(app.router). In fact, app.use(app.router) should be the last thing you call.
The Content-Type in request header is really important, especially when you post the data from curl or any other tools.
Make sure you're using some thing like application/x-www-form-urlencoded, application/json or others, it depends on your post data. Leave this field empty will confuse Express.
First make sure , you have installed npm module named 'body-parser' by calling :
npm install body-parser --save
Then make sure you have included following lines before calling routes
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
As already posted under one comment, I solved it using
app.use(require('connect').bodyParser());
instead of
app.use(express.bodyParser());
I still don't know why the simple express.bodyParser() is not working...
Add in your app.js
before the call of the Router
const app = express();
app.use(express.json());
The question is answered. But since it is quite generic and req.body undefined is a frequent error, especially for beginners, I find this is the best place to resume all that I know about the problem.
This error can be caused by the following reasons:
1. [SERVER side] [Quite often] Forget or misused parser middleware
You need to use appropriate middleware to parse the incoming requests. For example, express.json() parses request in JSON format, and express.urlencoded() parses request in urlencoded format.
const app = express();
app.use(express.urlencoded())
app.use(express.json())
You can see the full list in the express documentation page
If you can't find the right parser for your request in Express (XML, form-data...), you need to find another library for that. For example, to parse XML data, you can use this library
You should use the parser middleware before the route declaration part (I did a test to confirm this!). The middleware can be configured right after the initialization express app.
Like other answers pointed out, bodyParser is deprecated since express 4.16.0, you should use built-in middlewares like above.
2. [CLIENT side] [Rarely] Forget to send the data along with the request
Well, you need to send the data...
To verify whether the data has been sent with the request or not, open the Network tabs in the browser's devtools and search for your request.
It's rare but I saw some people trying to send data in the GET request, for GET request req.body is undefined.
3. [SERVER & CLIENT] [Quite often] Using different Content-Type
Server and client need to use the same Content-Type to understand each other. If you send requests using json format, you need to use json() middleware. If you send a request using urlencoded format, you need to use urlencoded()...
There is 1 tricky case when you try to upload a file using the form-data format. For that, you can use multer, a middleware for handling multipart/form-data.
What if you don't control the client part? I had a problem when coding the API for Instant payment notification (IPN). The general rule is to try to get information on the client part: communicate with the frontend team, go to the payment documentation page... You might need to add appropriate middleware based on the Content-Type decided by the client part.
Finally, a piece of advice for full-stack developers :)
When having a problem like this, try to use some API test software like Postman. The object is to eliminate all the noise in the client part, this will help you correctly identify the problem.
In Postman, once you have a correct result, you can use the code generation tool in the software to have corresponded code. The button </> is on the right bar. You have a lot of options in popular languages/libraries...
app.use(express.json());
It will help to solve the issue of req.body undefined
// Require body-parser (to receive post data from clients)
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Looks like the body-parser is no longer shipped with express. We may have to install it separately.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
Refer to the git page https://github.com/expressjs/body-parser for more info and examples.
In case anyone runs into the same issue I was having; I am using a url prefix like
http://example.com/api/
which was setup with router
app.use('/api', router);
and then I had the following
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
What fixed my issue was placing the bodyparser configuration above app.use('/api', router);
Final
// setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//this is a fix for the prefix of example.com/api/ so we dont need to code the prefix in every route
app.use('/api', router);
Most of the time req.body is undefined due to missing JSON parser
const express = require('express');
app.use(express.json());
could be missing for the body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
and sometimes it's undefined due to cros origin so add them
const cors = require('cors');
app.use(cors())
The middleware is always used as first.
//MIDDLEWARE
app.use(bodyParser.json());
app.use(cors());
app.use(cookieParser());
before the routes.
//MY ROUTES
app.use("/api", authRoutes);
express.bodyParser() needs to be told what type of content it is that it's parsing. Therefore, you need to make sure that when you're executing a POST request, that you're including the "Content-Type" header. Otherwise, bodyParser may not know what to do with the body of your POST request.
If you're using curl to execute a POST request containing some JSON object in the body, it would look something like this:
curl -X POST -H "Content-Type: application/json" -d #your_json_file http://localhost:xxxx/someRoute
If using another method, just be sure to set that header field using whatever convention is appropriate.
Use app.use(bodyparser.json()); before routing. // .
app.use("/api", routes);
History:
Earlier versions of Express used to have a lot of middleware bundled with it. bodyParser was one of the middleware that came with it. When Express 4.0 was released they decided to remove the bundled middleware from Express and make them separate packages instead. The syntax then changed from app.use(express.json()) to app.use(bodyParser.json()) after installing the bodyParser module.
bodyParser was added back to Express in release 4.16.0, because people wanted it bundled with Express like before. That means you don't have to use bodyParser.json() anymore if you are on the latest release. You can use express.json() instead.
The release history for 4.16.0 is here for those who are interested, and the pull request is here.
Okay, back to the point,
Implementation:
All you need to add is just add,
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(app.router); // Route will be at the end of parser
And remove bodyParser (in newer version of express it is not needed)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
And Express will take care of your request. :)
Full example will looks like,
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true}));
app.post('/test-url', (req, res) => {
console.log(req.body)
return res.send("went well")
})
app.listen(3000, () => {
console.log("running on port 3000")
})
You can try adding this line of code at the top, (after your require statements):
app.use(bodyParser.urlencoded({extended: true}));
As for the reasons as to why it works, check out the docs: https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions
Firsl of all, ensure you are applying this middleware (express.urlencoded) before routes.
let app = express();
//response as Json
app.use(express.json());
//Parse x-www-form-urlencoded request into req.body
app.use(express.urlencoded({ extended: true }));
app.post('/test',(req,res)=>{
res.json(req.body);
});
The code express.urlencoded({extended:true}) only responds to x-www-form-urlencoded posts requests, so in your ajax/XMLHttpRequest/fetch, make sure you are sending the request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); header.
Thats it !
in Express 4, it's really simple
const app = express()
const p = process.env.PORT || 8082
app.use(express.json())
This occured to me today. None of above solutions work for me. But a little googling helped me to solve this issue. I'm coding for wechat 3rd party server.
Things get slightly more complicated when your node.js application requires reading streaming POST data, such as a request from a REST client. In this case, the request's property "readable" will be set to true and the POST data must be read in chunks in order to collect all content.
http://www.primaryobjects.com/CMS/Article144
Wasted a lot of time:
Depending on Content-Type in your client request
the server should have different, one of the below app.use():
app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))
Source: https://www.npmjs.com/package/body-parser#bodyparsertextoptions
Example:
For me,
On Client side, I had below header:
Content-Type: "text/xml"
So, on the server side, I used:
app.use(bodyParser.text({type: 'text/xml'}));
Then, req.body worked fine.
To work, you need to app.use(app.router) after app.use(express.bodyParser()), like that:
app.use(express.bodyParser())
.use(express.methodOverride())
.use(app.router);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
This saved my day.
I solved it with:
app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});
In my case, it was because of using body-parser after including the routes.
The correct code should be
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use(userRoutes);
app.use(adminRoutes);
As I get the same problem, although I know BodyParser is no longer used
and I already used the app.use(express.json())
the problem was {FOR ME}:
I was placing
app.use(express.json())
after
app.use('api/v1/example', example) => { concerns the route }
once I reorder those two lines;
1 - app.use(express.json())
2 - app.use('api/v1/example', example)
It worked perfectly
If you are using some external tool to make the request, make sure to add the header:
Content-Type: application/json
This is also one possibility: Make Sure that you should write this code before the route in your app.js(or index.js) file.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

Resources