Cant get form data on a POST request - javascript

im trying to get the params of my post request. I can send them with JSON and it will work (if i take out the type property of the BodyParser.json) but not form data. Im using the body-parser middleware as follows.
const BodyParser = require('body-parser')
const Config = require('../config/environment');
const Express = require("express");
const App = Express();
App.use(BodyParser.json({type: '/', limit: '50mb'}));
App.use(BodyParser.urlencoded({extended: false}));
App.listen(3000, () => {Response.logger('Api running on port 3000.');});
App.post("/signup", (req, res, next) =>
{
consoleAlert('SIGNUP', false);
console.log(req);
Account.signup(req.params).then(
function(results) {response(results, res, 'SIGNUP');},
function(error) {response(error, res, 'SIGNUP');});
});
So when i print out req, the body is always empty with form data

Written from scratch - this appears to work:
server:
//app.js
const express = require('express');
const bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', function(req, res, next) {
console.log(req.body);
});
app.listen(3022);
client: call curl from command line sending form data (application/x-www-form-urlencoded is the default), mine node server IP is 10.10.1.40 :
curl -d "param1=value1&param2=value2" -X POST http://10.10.1.40:3022/

Related

Node.js req.body undefined in form-data content-type

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.

Node.js express - body of POST request is always empty

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

Req.Body is returning "undefined" values

I have added body-parser to my application app.js file. I have a routes folder and a controllers folder which handles my request.
Initially, I did not have body-parser added to my application. When I added body-parser and console logged req.body I got an empty object. When I console logged req.body.email, req.body.password, and req.body.displayName values from postman were read as undefined.
app.js
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
let bodyParser = require('body-parser');
let assert = require('assert');
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config()
}
let usersRouter = require('./routes/user');
let app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/user', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// MongoDB Connection
const db = {};
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(process.env.MONGODB_CONNECT_URL, (err, client) => {
// Connection works dont worry about it
});
module.exports = app;
routes/user.js
const express = require('express');
const router = express.Router();
const user = require('../controllers/user');
router.post('/', user.createUser);
router.delete('/:id', user.deleteUser);
router.get('/:id', user.loginUser);
module.exports = router;
controllers/user.js
const bcrypt = require('bcryptjs');
const Joi = require('joi');
const ObjectId = require('mongodb').ObjectID;
exports.createUser = async (req, res, next) => {
console.log('Request body: ', req.body);
const email = req.body.email;
const password = req.body.password;
const displayName = req.body.displayName;
console.log('Email: ', email);
console.log('Password: ', password);
console.log('Display name: ', displayName);
};
Please make sure that you are adding content-type header in postman content-type : application/json also in body tab select raw and beside raw select json from drop-down list.
Check this
https://i.stack.imgur.com/ZDhcl.png
You are probably trying to send form-data with Postman which sends a multipar body, body parser cannot handle multipart bodies. For handling multipart bodies you have to use a different module, I normally use multer.
With multer installed you just have to include it and it as middleware (under you body-parser for instance) using none() since in this case you want to handle text-only multipart body (More information about this in multer docs
let multer = require('multer');
app.use(multer().none());
Besides that I wanted to mention you are including two body parsers in your code, the express body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
and an external body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Pick one, you don't need both, the best option for me would be to keep the one that comes with express, this way you don't have to install any more external packages.

Calling node api through postman with response as enable javascript error

When calling API https://mywebsite.com/api/register through browser and it returns correct response from server as { "error": false, "message": "Hello World" }
If we hit the same request from postman then it returns with some html content as Please enable JavaScript to view the page content.
Below is node side code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
router.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
The api working through the browser but not with postman. What will be the possible errors?
If you want to separate the router files then use the following pattern otherwise use app.get()
app.js
var express = require('express'),
car = require('./routes/car'),
bus = require('./routes/bus');
var app = express();
app.use('/car', car);
app.use('/bus', bus);
app.listen(2000);
car.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.send('GET handler for /car route.');
});
router.post('/', function(req, res) {
res.send('POST handler for /car route.');
});
router.put('/', function(req, res) {
res.send('put handler for /car route.');
});
module.exports = router;
Try this instead:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', "extended": false }));
app.listen(8080);
app.get("/", function (req, res) {
res.json({ "error": false, "message": "Hello World" });
});
Replace router.get with app.get.
I test your code on my browser and it doesn't work too.

Return different HTTP response codes for a REST End Point

I'm using express to serve the REST API endpoints for a mocked backend. For one of the endpoints, I'd like to be able to return different http response codes, with the other endpoints continuing to return 200. My code currently looks something like this:
var port = 32000;
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded({ extended: true }) );
var setHeaders = function(req, res) {
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "http://localhost:2000");
};
app.get("*", setHeaders);
app.listen(port, function () {});
app.get("my/enpoint/one", function(req, res){
res.send('hello');
});
You can use res.status to set the HTTP code:
res.status(404).send('Bad Request');

Categories