Node.JS body parser issue - javascript

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

Related

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

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

Node express request call inside get

I'm trying to use nodejs as a layer between my public website and a server on the inside of our network.
I'm using express.js to create a simple REST api. The API endpoint should trigger a request call to a webservice, and return the result.
But the request call inside my .get() function doesn't do anything.
I want to return the result from the nested call to be returned.
Code:
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is workiung on IISNode')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
res.send('Customer ID: ' + req.params.customerId + ' Invoice ID: '+ req.params.invoiceId)
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request('http://www.google.com', function (error, response, body) {
res.send(body);
})
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Any suggestions?
You can write in this way
// Dependencies
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
//Port
var port = process.env.PORT || 8080;
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.get('/invoice', function(req, res){
res.send('Express is working')
});
app.get('/invoice/api/costumer=:customerId&invoice=:invoiceId', function(req, res){
var url = 'http://xxx/invapp/getinvoice?company='+req.params.customerId+'S&customerno=13968&invoiceno='+req.params.invoiceId+'';
request(url, function (error, response, body) {
var data={
body:body,
customerID:req.params.customerId,
invoiceID:req.params.invoiceId
};
res.send(data);
});
});
// Start server
app.listen(port);
console.log("API is running on port " + port);
Please find the snippet I am using. Hope this helps for you as well.
var body="";
function callyourservice(customerId,invoiceId,callback) {
var options = {
uri : url + 'costumer=:customerId&invoice=:invoiceId',
method : 'GET'
}
request(options, function (error, response, body) {
console.log(response);
if (!error && response.statusCode == 200) {
res = body;
}
else {
res = 'Not Found';
}
callback(res);
});
}
callyourservice("customerId value","invoiceId value", function(resp){
body=JSON.stringify(resp);;
});
You can write callyourservice inside a get method from client like
app.get('/'){
}
You can try doing it the node way using pipe
var http = require('http');
http.createServer(function(request, response) {
var proxy = http.createClient(9000, 'localhost')
var proxyRequest = proxy.request(request.method, request.url, request.headers);
proxyRequest.on('response', function (proxyResponse) {
proxyResponse.pipe(response);
});
request.pipe(proxyRequest);
}).listen(8080);
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to port 9000!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
You can find the reference here

cookie doesn't get sent on first request

I've got the following code on my server.js express application:
var express = require('express');
var fallback = require('express-history-api-fallback');
var compress = require('compression');
var favicon = require('serve-favicon');
var prerenderio = require('prerender-node');
var config = require('getconfig');
var app = express();
app.use(function (req, res, next) {
if (config.environment !== 'local') {
res.cookie('config', JSON.stringify(config), { secure: true });
}
else {
res.cookie('config', JSON.stringify(config));
}
next();
});
app.get('/versioncheck', function(req, res) {
return res.json({ version: config.version });
});
app.use(compress());
app.use(prerenderio.set('prerenderToken', config.prerender_token).set('protocol', 'https'));
app.use(express.static(__dirname, { maxAge: 31536000 }));
app.use(favicon(__dirname + '/favicon.ico'));
app.use(fallback('index.html', { root: __dirname }));
const PORT = process.env.PORT || 1010;
app.listen(PORT, function () {
console.log('Server started on port %s', PORT);
});
The first middleware I'm setting up with express is quite simple: It sends down a cookie to the client with some config information. The issue I'm facing is that this cookie doesn't get sent down to the client upon first request. For all subsequent requests it does work fine. What am I missing?
I had a similar problem some time ago.
At the begin of the first request, the cookie does not exist.
The cookies get sent during the request, not before.
So, at the begin of the second request, the cookie is set (from request 1).

Unable to parse url encoded data in express

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.

Categories