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

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 }));

Related

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.

Get empty req.body when deployed on Heroku

I have a react app front end posting data to my server(use express) deployed on Heroku. Code works well when both client and server running on localhost, but when it's on Heroku, the req.body always gets empty object {}.
Can anyone point out what's going wrong here? Thanks in advance :)
React code:
axios.post("/api", data, {headers: { "Content-Type": "application/json;charset=utf-8" }})
Express code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(
cors({origin: URL,credentials: true}));
app.post("/api", (req, res) => {const data = req.body; console.log(data);};
This run perfectly on my computer. The log and the response works just fine. Hope it helps. I think the problem could be you are sending a GET request instead of a POST request.
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors({origin: new URL('http://localhost:3000'), credentials: true})) // Add this 'new' keyword to URL
app.post("/api", (req, res) => {
const data = req.body
console.log(data)
res.send(data) // Added this to allow request to end
})
// Added this part to start the server listen.
const port = process.env.PORT || 3000
app.listen(port , () => {
console.log('Server is running on port '+3000)
})

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

Warning message while running nodejs file

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');

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