How to create Node server only for POST requests - javascript

I need to create a Node server only for receiving POST requests. With the information in the body of the request, I need to create a system call. How do I do so? So far, I only have:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser);
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
});
port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)
However, when I make a POST request to 127.0.0.1:3000, the body is undefined.
var request = require('request');
request.post(
'127.0.0.1:3000',
{ form: { "user": "asdf" } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);

You've got a middleware problem here. The express.bodyparser() middleware is deprecated in Express 4.x. This means you should be using the standalone bodyparser middleware.
Oddly enough, you're importing the correct middleware by doing:
var bodyParser = require('body-parser');
However, you should be using it differently. Take a look at the docs and the example given:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})

var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
In the newest version of express, express.bodyParser is not used. See the reference

Related

Express js get request is showing on the html page

Im new in express.js so i would like to know why when I'm sending a data to client the data is showing in the browser but I'd like to send it in preview please can you take a look what I do wrong?
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/getProducts', (req,res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type','application/json');
res.json(obj);
});
first you need install dependencies like body-parse cors, then you need listen port like this
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/getProducts', (req, res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type', 'application/json');
res.json(obj);
});
app.listen(3000)

Express does not show request body on form data on using body parser and multer

In Index.js I have added bodyparser and bodyparser url encoder as middleware.
const bodyParser = require("body-parser");
require("dotenv").config();
const PORT = process.env.PORT || 3032;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
In other file I have just console logged the request body and it logs out an empty object.
webhooks.post("/webhooks/", async (req, res) => {
console.log(req.body);
res.send("ok");
});
the res.body is still {}

Express Body Parser with both JSON and binary data passing capability

In my express app router, I've routes for accepting POST request of JSON data as well as binary data. The problem is when I use body parser for passing JSON data, it also considers the binary data as JSON and gives error while POSTing binary data. i.e. when I use:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
And When I remove this, It only works for binary data. Following is my route for POSTing binary file.
router.post('/file', function (req, res) {
var gridfs = app.get('gridfs');
var writeStream = gridfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
I've also tried moving this file route to other router. In that case, when I don't set anything regarding body parser, it still gives the same error.
One fix that works correctly is placing this file route in my main app.js prior to setting body parser. But I think this would not be good approach. I want these routes to be in separate files.
So what I'm missing here? Any alternatives will also be appreciated.
EDIT
As per the answer, I've first separated out my routers which requires body parsing and which do not. Also removed the bodu parser from my main app.use() Now in the router in which, I need body parser, I've added those 2 lines. But the behavior is same.
When I add those 2 lines, only JSON reqquest works and when I remove, only binary POST req. works.
Here is my updated code:
app.js
const express = require('express');
const app = module.exports = express();
const bodyParser = require('body-parser');
const port = 8080;
// //parsing incoming requests using body-parser middlewares
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false}));
//adding routes
app.use(require('./routes/additionRouter'));
app.use(require('./routes/mediaRouter'));
//catch 404 file not found here
app.use((req, res, next) => {
const err = new Error('Page Not Found');
err.status = 404;
next(err);
});
//Error Handler
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send(err.message);
});
app.listen(port, () => {console.log('Server listening on port: ' + port)});
additionRouter.js
const express = require('express');
const router = express.Router();
var exported = require('../config/dbConnection');
const bodyParser = require('body-parser');
// parsing incoming requests using body-parser middlewares
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false}));
//Endpoint for adding new challenge
router.post('/endpoint1', (req, res, next) => {
});
module.exports = router;
and mediaRouter.js
const express = require('express');
const mediaRouter = express.Router();
const exported = require('../config/dbConnection');
exported.cb((gridfs) => {
//For adding media files to database named 'mediadb'
//POST http://localhost:8080/file
mediaRouter.post('/file', function (req, res) {
// var gridfs = app.get('gridfs');
var writeStream = gridfs.createWriteStream({
filename: 'file_name_here'
});
writeStream.on('close', function (file) {
res.send(`File has been uploaded ${file._id}`);
});
req.pipe(writeStream);
});
//GET http://localhost:8080/file/[mongo_id_of_file_here]
mediaRouter.get('/file/:fileId', function (req, res) {
// var gridfs = app.get('gridfs');
gridfs.createReadStream({
_id: req.params.fileId // or provide filename: 'file_name_here'
}).pipe(res);
});
});
module.exports = mediaRouter;
By specifying
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
your entire app uses the body parser middleware. You could create another middleware to handle whether or not the body parser is used. For example:
const bodyParse = bodyParser.json();
app.use((req, res, next) => {
if(req.originalUrl == "restOfUrl/file") next();
else bodyParse(req, res, next);
});

Express router post function not working

Declaration:
var express = require('express');
var router = express.Router();
Route.js: Post call here
router.route('/signup')
.post(function (req, res) {
console.log('post signup called', req.body);
res.json({message: 'signup'});
});
module.exports = router;
The req.body is always undefined. I am able to print them console inside ajax call. I don't understand req.body is undefined. What am I missing?
Ajax post data sent like:
$.ajax({
url: '/signup',
type: 'POST',
data: params,
success: function (res) {
console.log('res', res);
},
error: function (err) {
console.log('err', err);
}
});
server js: Already using body-parser here
var express = require("express");
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var request = require("request");
var router = require('./app/routes/route.js');
var functions = require('./app/functions/functions.js');
var http = require('http');
var https = require('https');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');
var model = require('./app/model/model.js');
app.use('/', express.static(__dirname + '/public_html'));
app.use('/', router);
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
Your requests won't be passed through body-parser because you're declaring it after the router (Express passes requests through middleware and routes in order of declaration; if a request can be handled by router, it won't be passed through the body-parser middleware anymore):
app.use('/', express.static(__dirname + '/public_html'));
app.use('/', router);
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
If you move body-parser to the front, it should work better:
app.use('/', express.static(__dirname + '/public_html'));
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({ limit: '5mb', extended: false }));
app.use('/', router);
You have to use body-parser
https://www.npmjs.com/package/body-parser
express.use(bodyParser.json());

When using ExpressJS and body-parser req.body is empty

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
oracledb.autoCommit = true;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
router.use('/' , function(req, res , next) {
console.log('Something is happening.');
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/insert')
.post(function(req, res) {
console.log(req.body);
console.log(req.body.c1);
console.log(req.body.c2);
});
app.use('/api', router);
app.listen(port);
In the example above ,when I try to log req.body it is returned as empty along with any of its properties.
EDIT: Maybe unrelated but when I try to test this REST API with a extension like Postman , it just keeps processing indefinately. ( Same thing happens with extension called DHC Rest)

Categories

Resources