Have a problem with using another method in class. I'm working with express framework and have to use Ecma Script 6. When I try to use method in the same class I have an error
const express = require('express');
var bp = require('body-parser');
const fd = express();
fd.use(bp.json());
fd.use(bp.urlencoded({ extended: true }));
fd.post('/', function(req, res){
console.log(req.body);
});
Related
My application has post route that accepts the data from postman client. I have written following code to retrieve value of form and print it:
var express = require('express');
req.app.use(express.urlencoded());
req.app.use(express.json());
console.log('req.body.name --> ' + req.body.name);
Above code prints req.body.name --> undefined rather than name value given in field name
I also tried following code:
var express = require('express');
const bodyParser = require('body-parser');
req.app.use(bodyParser.urlencoded({ extended: true }));
console.log('req.body.name --> ' + req.body.name);
Above code too prints req.body.name --> undefined rather than name value given in field name.
Can anyone please guide me on to resolve the issue in retrieving field name?
Used multer to solve this based on inputs from req.body is empty on express POST call.
Posting to benefit others.
var multer = require('multer');
var upload = multer() ;
app.post('/test', upload.array(), function (req, res, next) {
console.log(req.body.name);
});
Cheers :)
In your code, req is used, but req is not declared.
You wrote that you used POST, but you didn't write an entry point for POST.
Please try the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
app.post('/users', (req, res) => {
console.log(req.body);
console.log(req.body.name);
res.send(req.body.name);
});
app.listen(3000);
The port number is not necessarily 3000.
Use your Postman configuration.
In your code, proper imports are not there.
1. For Any node application these imports are mandatory
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
2. Use these imports properly like
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
3. Then use any Http Method like Get, Post, Put, and Delete
Example -
app.post(‘/sample’, (req, res) => {
// name must be in your request body while requesting for the above API
console.log(req.body.name);
res.send(req.body.name);
});
4. Add the port lister on which Application should run
app.listen(9000);
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.
When I send a POST request using postman to localhost:8080/api/newUser with request body:
{name: "Harry Potter"}
At server end console.log(req.body) prints:
{ '{name: "Harry Potter"}': '' }
server.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
router.use(function(req, res, next) {
next();
});
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);
app.listen(8080);
What am I doing wrong?
In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use('/api', router);
app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
Extracting the key (which should contain the entire
object)
Parsing the key
Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]
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);
});
The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.