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);
});
Related
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.
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¶m2=value2" -X POST http://10.10.1.40:3022/
I'm trying to receive a callback from the Dribbble Auth API. The Authentication process is working fine until I'm trying to fetch the response data with NodeJS.
My Callback-URL is http://localhost:8080/callback
A callback url looks like this http://localhost:8080/callback?code=11ee328ab7935bd7240cbff0a2d0b8c93e96547e0a3&state=aoksdmSAOKDm
I'm using body-parser and multer.
var express = require("express");
var multer = require("multer");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var upload = multer({ storage: multer.memoryStorage() });
var app = express();
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "../webapp/")));
app.get("/callback", upload.single("code"), (req,res) => {
console.log(req.body);
res.send()
}
The response in the console is undefined
the query isn't in req.body with a GET request. you have to do:
req.query
You are sending a GET request.Please check
req.query
More details refer
http://expressjs.com/en/api.html
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');
Trying to access the body of an incoming text message with Twilio.
var express = require('express');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
...
module.exports = function(app) {
...
app.post('/twilio/message', jsonParser, function(request, response) {
var twiml = new twilio.TwimlResponse();
twiml.message('test body is ' + request.Body);
// I also tried JSON.stringify(request.body) to see what was in body and it returned '{ñ'
response.type('text/xml');
response.send(twiml.toString());
});
}
The following returns 'test body is undefined'. Not sure what I'm doing wrong the request data seems to be there and I can access request.url.
Edit: Question updated with attempt to use body-parser library.
I'm taking Twilio out of this equations (it's not the issue here). Also remember to npm install body-parser --save.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// listen for POSTs on /twilio/message
app.post('/twilio/message', function(req, res){
console.log(req.body);
res.end("End");
});
// start express
app.listen(8888);
You can test this with Postman (make sure you set x-www-form-urlencoded as your body data (or use raw with application/json) to test.
I just did to make sure it works.
I've worked with Twilio in the past and this is exactly the code we used to parse the body.