Unable to parse url encoded data in express - javascript

I have this super simple server:
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/update', (req, resp) => {
debugger;
resp.send();
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Using postman, I am sending data to the server like this:
REPL shows me an empty body when the request is received:
> req.body
{}
I would expect the body to look something like this:
{
"hello": "world"
}
Am I missing something obvious ? Probably ..

By choosing x-form-urlencoded below postman will send the Content-Type header for you, you dont need to specify it again yourself. You can see this by clicking the Preview button. So you're sending a duplicate Content-Type header which seems to trip up body parser.

Related

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

Node JS POST request returning undefined body

Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.
I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.
I have added body-parse as suggested but still no joy.
I will post my server code and request below.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.post('/api/save-json', (req, res) => {
console.log(req);
res.send(
`I received your POST request. This is what you sent me: ${req.body.json}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
My postman request is:
{
"body" :
{
"json": "some data"
}
}
Any ideas?
body is the property in the req object containing the HTTP request body (which is set by body-parser), since you're sending in an object called body you'll need to access it like this: req.body.body.json

Accessing Twilio SMS Meta-Data?

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.

Ignore header validation for HTTP requests in Node

I am building a proxy server which is supposed to forward data from an Shoutcast server to the client. Using request or even Node's http module this fails due to missing HTTP header:
{ [Error: Parse Error] bytesParsed: 0, code: 'HPE_INVALID_CONSTANT' }
The URL in question is: http://stream6.jungletrain.net:8000
Doing a header request with curl I was able to verify this:
$ curl -I http://stream6.jungletrain.net:8000
curl: (52) Empty reply from server
Yet the stream is working fine as tested with curl stream6.jungletrain.net:8000.
Is there a way to disable the header verification in request or Node's http? This is the code I am testing it on:
var express = require('express');
var request = require('request');
var app = express();
app.get('/', function (req, res) {
request('http://stream6.jungletrain.net:8000').pipe(res);
stream.pipe(res);
});
var server = app.listen(3000, function () {
console.log('Server started')
});
I am aware this can be achieved by rolling an implementation with net, there is also icecast-stack but subjectively seen it only implements half of the Stream interfaces properly.
Using icecast, I was able to get this working both using the on('data') event and by piping it to the Express response:
var express = require('express');
var app = express();
var icecast = require('icecast');
var url = 'http://stream6.jungletrain.net:8000';
app.get('/', function(req, res) {
icecast.get(url, function(icecastRes) {
console.error(icecastRes.headers);
icecastRes.on('metadata', function(metadata) {
var parsed = icecast.parse(metadata);
console.error(parsed);
});
icecastRes.on('data', function(chunk) {
console.log(chunk);
})
});
});
var server = app.listen(3000, function() {
console.log('Server started')
});
Or simply:
app.get('/', function(req, res) {
icecast.get(url).pipe(res);
});
Also of some note:
It appears the icecast package has been superseded by https://www.npmjs.com/package/icy

Node.JS body parser issue

I'm attempting to send data from one machine to another in node.js.
I seem to be having some difficulty getting the parser to function correctly.
Here is my client and server code
Client.JS
var request = require('request');
request.post(
'http://192.168.1.225:3002',
{ form: { key: 'notyourmother' } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
Server.JS
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.json());
app.post('/', function (req, res) {
res.send('POST request to the homepage');
console.log(req.body);
});
var server = app.listen(3002, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
When I run both snippets, the console outputs "{}".
What may I be doing incorrect?
Thank you!
You're using the wrong body parser on the server side. request is sending a application/x-www-form-urlencoded request payload with your current client code. So simply swap out bodyParser.json() with something like bodyParser.urlencoded({ extended: false }).

Categories