Warning message while running nodejs file - node.js

I am beginner in node js, i worte a code to get the form data from html using express and it allways shows the warning.
"body-parser deprecated undefined extended: provide extended option app.js:11:17"
here is my code
const express = require('express')
const path = require('path')
const app=express()
const port=process.env.PORT || 3000
const publicDirectoryPath = path.join(__dirname, '')
app.use(express.static(publicDirectoryPath))
app.use(express.urlencoded())
app.use(express.json())
app.get('',(req,res)=>{
res.render('index')
})
app.post('/login',(req,res)=>{
try{
console.log(req.body)
res.send('thankyou for submission')
}catch(error){
res.send()
}
})
app.listen(port,()=>{
console.log('server started to'+port);
})

you need to replace
app.use(express.urlencoded())
with
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
and dont forget to require bodyparser
var bodyParser = require('body-parser');

You have to provide the option "extended" when using the bodyParser since the default value is going to change. Use this on line 11:
app.use(bodyParser.urlencoded({ extended: true }));
Also include the bodyParser module with:
const bodyParser = require('body-parser');

Related

Though deprecated, shouldn't body-parser still work?

Though body-parser has been deprecated, it should still work.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express(); //this is a new instance of express
app.use(express.static("public"));
app.use(bodyParser, urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
Console output using body-parser
[app crash error](https://i.stack.imgur.com/fkLVH.png)
And my code with body-parser commented out...
const express = require("express");
//const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express(); //this is a new instance of express
app.use(express.static("public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
//app.use(bodyParser, urlencoded({ extended: true }));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
This works and my app doesn't crash
Please refer to the docs on how to use body-parser. https://www.npmjs.com/package/body-parser
app.use(bodyParser.urlencoded({ extended: true }));

body parser logging empty object in express router

for some reason I can see my req.body in my express server on my route
req body is [Object: null prototype] { '{"password":"xxxxxxxx"}': '' }
but when I log req.body.password (the object key) I get
req body is undefined
here's my index router for reference in my express app
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const path = require('path');
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
To access the content of the body, Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
You need to install a body-parser package.
npm i body-parser --save
Now import body-parser in your project.
It should be called before your defined route functions.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const path = require('path');
app.use(bodyParser.json());
app.use(bodyparser.urlencoded({ extended : true }));
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
If you're using body-parser
You have to enable the body parser to work, before using parsed data in you routes.
In your main module where you import all your libs, you need to declare express to use body-parser middleware.
const express = require('express')
const bodyparser = require('body-parser')
const app = express()
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended : true }))
...
//here comes your routes
After including the bodyparser middleware you can use parsed data in your routes.
Notice that if you're using express version >= 4.16, body parser comes bundled with express. You just have to use change your code to:
const express = require('express')
const app = express()
app.use(express.json()); //this line activates the bodyparser middleware
app.use(express.urlencoded({ extended: true }));
Doing so you can safely remove body-parser package.

Cannot GET api express application

I got this error "Cannot GET /api/data"
it s working good on my local host , but when I upload it to server it show me this error,
this is a simple code for testing that also show me the same .
my index page
const express = require('express');
const bodyparser = require('body-parser');
const mysql = require('mysql');
const port = 4000;
const route = require('route');
const data = require('./routes/data.js');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.use('/data', data);
app.listen(port, () => {
console.log("working");
});
/routes/data.js file
const express = require('express');
const router = express.Router();
const add = require('../classes/insert');
const bodyparser = require('body-parser');
var con = require('../Modules/connection');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.get("/",(req, res)=>{
res.send("hello");
});
module.exports = router;
app.use('/data', data)
This will only work on /data route. If you want this work on /api/data, use the following snippet.
app.use('/api/data', data)
this error may be comming because of the file path. Try using __dirname in spite of ./ and also check your file structure.
Hope this works.

How to use bodyparser in node.js

When do I use bodyparser in my code?
const express = require('express');
const bodyparser = require('body-parser');
const app = express();
app.set('views',__dirname+'/public/pages/');
app.set('view engine','twig');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/',(req, res)=>{
res.render('index',{title:"create user"})
})
app.post('/',(req, res)=>{
console.log(req.body.username);
})
app.listen(8000, ()=>console.log('server is running at:http://localhost:8000'));
when I run this code:Errorenter image description here
you have const bodyparser = require('body-parser'); in lowercase ,then you use it with camelCase
bodyParser.urlencoded({ extended: false })
There is a spelling mistake just change bodyparser to bodyParser in second line of your code.
When do i use bodyparser in my code ?
npm page for the module says, "Node.js body parsing middleware.
Parse incoming request bodies in a middleware before your handlers, available under the req.body property."
read more here

ExpressJS Error: Body-Parser Deprecated

Question
I'm trying build a Node.js API, when write my server.js file, my code looks like this:
var express = require('express');
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.get('/api/posts', function(req,res) {
res.json([
{
username: 'oscar',
body: 'hello'
}
])
})
app.listen(3000, function() {
console.log('Server Listening on', 3000)
})
However, in the command prompt I am getting this error:
body-parser deprecated bodyParser: use individual json.urlencoded
middlewares server.js:4:11
body-parser deprecated undefined extended: provide extended option
node_modules\body-parser\index.js:85:29
I tried changing this to :
app.use(bodyParser.urlencoded({ extended: true }));
and
app.use(bodyParser.urlencoded({ extended: false }))
like other posts suggest, but it still gives the same error. Not sure what to do now! Please help.
Thanks!
var app = express();
// configure body-parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
I had similar deprecated warning. Here's my original code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
Adding {extended: true} fixed the warning for me. Here's changed code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Unless you have a typo, change:
var express = require('body-parser');
var app = express();
app.use(bodyParser.json());
to:
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
Do have a look at what the request and response objects do here
You don't actually need the line app.use(bodyParser.urlencoded({extended: true}));
I've got it to work with the following code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
As log as you have app.user(bodyParser.json()); you shouldn't get the error.
You don't need body-parser module any more with current express.js versions (≥ 4.16).
Instead, use the json parser already included in express:
app.use(express.json())
Source: https://expressjs.com/en/changelog/4x.html#4.16.0
Don't use body-parser
In new versions of express, body parsing is now builtin. So, you can simply use
app.use(express.json()) //For JSON requests
app.use(express.urlencoded({extended: true}));
from directly express
You can uninstall body-parser using npm uninstall body-parser
Then you can simply get the POST content from req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or for string JSON body, you can use this
var postData = JSON.parse(req.body);
});

Resources