To set up my bodyparser I use the following code:
const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
Now if I have the following POST route in my express router:
var router = require('express').Router();
router.post('/sendadvertisement', async (req, res) => {
console.log(req.body)
});
The result is [Object: null prototype] {advertisement: 'test'}
-> My req.body isn't empty because it's in json format in my console output.
I don't really understand how this result can happen because I defined that the body should be in json format.
I also tried it with app.use(express.json()), doesn't work either.
I replaced router with app and everything worked fine.
Router.get/post etc is only for defining sub routes after after you mounted a middelware function like app.use('route') that handels the Route. If you want to use the router you should mount the route using app.use(...) and then declare the post using router.post(...)
Also See: Difference Between app.use() and router.use() in Express
const express = require('express')
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.post('/sendadvertisement', async (req, res) => {
console.log(req.body)
});
app.listen(8000, () => {
console.log('Example app listening on port 8000!')
});
If you are using express then you can use this code to set your body parser.
app.use(express.json( {extended:false} ));
app.use(express.urlencoded({extended: false}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
This is also giving error, page is scrolling after submission.
Related
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.
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);
});
I have simply express server:
const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const bodyparser = require('body-parser');
const app = express();
const hbs = exphbs.create({
defaultLayout: 'main',
extname: 'hbs'
});
const _PORT = process.env.PORT || 80;
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
app.set('views', 'views');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json({ type: 'application/*+json' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(require('./routers/login'));
serverStart();
async function serverStart(){
try{
app.listen(_PORT);
console.log('[SERVER] Server is listening port ' + _PORT + ' now.');
}catch(error){
console.log(error);
}
}
And simply router:
const { Router } = require('express');
const router = Router();
router.get('/', async (req, res) => {
res.render('login', {
title: 'main page'
});
});
router.post('/', async (req, res) => {
console.log(req.body);
});
module.exports = router;
Why 'req.body' is always empty?
I tried to send POST query from "Postman", but it isn't work.
It's working only with x-www-form-urlencoded query, but I want to send json query.
P.S. Sorry for my english.
UPD: postman screenshot
link
I've been try your code and it's working fine, you only have to change your code:
app.use(bodyparser.json({ type: 'application/*+json' }));
With this code below:
app.use(bodyparser.json({ type: 'application/json' }));
Note: If you're use the latest version of express, then you should not to install body-parser, Because body-parser is already included.
So, you can use this code below:
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
I hope it can help you.
In this example below, you can see that the csrfProtection and parseForm functions are passed as parameters/callbacks in the GET and POST requests...
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// setup route middlewares
var csrfProtection = csrf({ cookie: true })
var parseForm = bodyParser.urlencoded({ extended: false })
// create express app
var app = express()
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.get('/form', csrfProtection, function(req, res) { // HERE
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', parseForm, csrfProtection, function(req, res) { // AND HERE
res.send('data is being processed')
})
However, if you are using a router, like I am, how can use these same functions? I am aware that by "using" them in app.js, they are made available on the req object but in the example given above, they are required as the 2nd and 2nd & 3rd arguments of the GET and POST routes, but req isn't made available until you're inside the final callback?!
So I know you can't do the below (just as an example)... so how should you use them? Would I have to re-declare them in every routes file?
Separate routes file: routes/someroute.js
...
router
.post('/', req.body, req.csrfProtection, (req, res) => {
})
...
Thanks in advance :)
Reference: https://www.npmjs.com/package/csurf
UPDATE
Following comments below, I have made the following changes to my app.js file.
app.js
...
global.bodyParser = require('body-parser').urlencoded({extended: false});
app.use(global.bodyParser);
global.csrfProtection = csrf({ cookie: false });
...
routes/myroute.js
router
.post('/', global.bodyParser, global.csrfProtection, (req, res) => {})
However, when I restart the server I am seeing this error, which suggests that that the global function is not defined... what am I missing here? :-/
Error: Route.post() requires a callback function but got a [object Undefined]
I think you ask about sharing middlewares across all API/routes files
You can do it like this :
First in your main file lets call it server.js we use you're code
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// create express app
var app = express()
// setup route middlewares
app.use(bodyParser.urlencoded({ extended: false }))
// parse cookies
app.use(cookieParser())
//enable your JS API/route script.
const awesomeAPI = require('./awesomeApi.js');
app.use('/awesome', awesomeAPI );
app.listen(3000);
Now you have file let's calle it awesomeApi.js
const express = require('express');
const awesomeApi = express.Router();
awesomeApi.route('/')
.post(req,res => {
//req.body present here. And body parser middle ware works.
})
module.exports = awesomeApi;
Hope this helps.
Some links:
https://expressjs.com/en/guide/using-middleware.html
https://expressjs.com/en/4x/api.html#express
I've got a simple Express server that uses the body-parser module to access POST-parameters. The app looks like this:
/index.js:
'use strict';
const express = require('express');
const app = express();
const apiRouter = require('./api/routes.js');
// Set our port for the server application
const port = process.env.PORT || 8080;
// Register the routes for the /api prefix
app.use('/api', apiRouter);
// Start server
app.listen(port);
console.log('The server is running on port ' + port);
/api/routes.js:
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Configure app to use bodyParser(). This will let us get the data from a POST
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
// START ROUTES
router.post('/devices', (req, res) => {
console.log(req.body); // Returns {}
res.json(req.body);
});
module.exports = router;
The problem is that the req.body object is empty (Always returns an empty object {}). Since I already loaded the body-parser middleware I have no idea what else I can try. I hope you have any suggestions.
I used the app Postman for testing. It appeared that it sent the POST data as form-data instead of x-www-form-urlencoded. After changing this setting the data showed up.