I have the following code:
var express = require('express');
var app = express.createServer();
var request = require('request');
app.use(myMiddleware);
app.listen(5010);
var payload = { id: 1 };
request({
method: 'POST',
body:JSON.stringify(payload),
url: 'http://localhost:5000'
}, function(err, res, body) {
console.info("Request Done");
})
In my middleware code I want to parse the body and extract the request id, yet for some reason the following code doesn't work (payload is undefined):
var myMiddleware= function (req, res, next){
var payload = req.body;
if (payload.id === 1) console.info("first request!!!!!");
next();
}
When I try to print "payload" all I get is [object Object].
Could you please tell me how to extract the id, and how to print the attributes of the payload object?
Thanks,
Li
Solved by adding:
app.use(express.bodyParser());
and by adding the following to the request code:
json: true
After adding the json=true attribute I also removed JSON.stringify(...) from the body of the request (now I don't need to stringify the body since it expects a json object)
Thanks.
Related
In my NodeJS/Express app, I have API implementation which calls another external API.
For this, I am using npm request & request-promise libraries
How can I call API's that has path parameter?
const express = require('express');
const router = express.Router();
const rp = require('request-promise');
router.post('employee/:id', (req, res) => {
const id = req.params.id; // I dont know how to use this in request library
handleRequest(req, res);
})
function handleRequest(req, res) {
const id = req.params.id; // I dont know how to use this in request library options?
var options = {
method: req.method,
uri: 'http://api.anotherhost.com/external/'+ req.path,
body: req.body,
qs: req.query,
json: true
};
rp(options)
.then((success) => res.send(success))
.catch((err) => res.status(err.statusCode).send(err.message));
}
https://github.com/request/request
https://www.npmjs.com/package/request-promise
Update:-
This code so far works fine for other calls without path parameter.
Since request doesn't provide an option to add path parameters you have to format your request uri to include them, you can simply use string literals to do this:
const id = req.params.id;
var options = {
method: req.method,
uri: `http://api.anotherhost.com/external/${id}`,
body: req.body,
qs: req.query,
json: true
};
Keep in mind you must verify that the id format is valid.
I have a Node.js API using Express.js with body parser which receives a BSON binary file from a python client.
Python client code:
data = bson.BSON.encode({
"some_meta_data": 12,
"binary_data": binary_data
})
headers = {'content-type': 'application/octet-stream'}
response = requests.put(endpoint_url, headers=headers, data=data)
Now I have an endpoint in my Node.js API where I want to deserialize the BSON data as explained in the documentation: https://www.npmjs.com/package/bson. What I am struggling with is how to get the binary BSON file from the request.
Here is the API endpoint:
exports.updateBinary = function(req, res){
// How to get the binary data which bson deserializes from the req?
let bson = new BSON();
let data = bson.deserialize(???);
...
}
You'll want to use https://www.npmjs.com/package/raw-body to grab the raw contents of the body.
And then pass the Buffer object to bson.deserialize(..). Quick dirty example below:
const getRawBody = require("raw-body");
app.use(async (req, res, next) => {
if (req.headers["content-type"] === "application/octet-stream") {
req.body = await getRawBody(req)
}
next()
})
Then just simply do:
exports.updateBinary = (req, res) => {
const data = new BSON().deserialize(req.body)
}
You could as well use the body-parser package:
const bodyParser = require('body-parser')
app.use(bodyParser.raw({type: 'application/octet-stream', limit : '100kb'}))
app.use((req, res, next) => {
if (Buffer.isBuffer(req.body)) {
req.body = JSON.parse(req.body)
}
})
I am not able to get the data in the http post method of express nodejs.I am posting data from angular2. When i inspect in the network section of chrome, the payload is visible but the same data is received blank at app.post method.Please help me.
angular2 code
this.headers = new Headers();
this.headers.append('Content-Type', 'x-www-form-urlencoded');
let body = JSON.stringify({name:"Lionel Messi"});
return this.http
.post('http://localhost:8081/save',body
,this.headers);
}
nodejs code
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/save', function (req, res) {
console.log("Got a POST request for the homepage");
console.log(req.body);// output - {}
res.send('Hello POST');
})
Network Section in Chrome....payload is proper
alert method in node.js will not work . You need to use console.log("Hello");
Second thing is to get body data , use req.body.name
My way of writing code is like below and it works
$http({
method: 'POST',
url: 'http://localhost:8081/save',
data: {name:"Lionel Messi"}
})
.success(function(data) {
return data
})
.error(function(error) {
// handle error
});
Other way you can try is:
$http.post('http://localhost:8081/save', {name:"Lionel Messi"})
.then(function(data) {return data})
.catch(function() {console.log("Error Occured");});
You can do it like this-
Suppose you have sent username and password from your browser by post method.
app.post("/ url,function(request,response)
{ var username=request.body.username;
var password=request.body.password;})
I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})
I am trying to modify the response with the help of a proxy created using node-http-proxy.
However I am not able to access the response headers. I want to access the response headers since I would like to modify javascript files and send the modified javascript files to the client.
This is my code:
var httpProxy = require('http-proxy');
var url = require('url');
var i = 0;
httpProxy.createServer(function(req, res, next) {
var oldwriteHead = res.writeHead;
res.writeHead = function(code, headers) {
oldwriteHead.call(res, code, headers);
console.log(headers); //this is undefined
};
next();
}, function(req, res, proxy) {
var urlObj = url.parse(req.url);
req.headers.host = urlObj.host;
req.url = urlObj.path;
proxy.proxyRequest(req, res, {
host: urlObj.host,
port: 80,
enable: {xforward: true}
});
}).listen(9000, function() {
console.log("Waiting for requests...");
});
writeHead() doesn't necessarily have to be called with an array of headers, write() can also send headers if necessary.
If you want to access headers (or set them), you can use this:
res.writeHead = function() {
// To set:
this.setHeader('your-header', 'your-header-value');
// To read:
console.log('Content-type:', this.getHeader('content-type'));
// Call the original method !!! see text
oldwriteHead.apply(this, arguments);
};
I'm using apply() to pass all the arguments to the old method, because writeHead() can actually have 3 arguments, while your code only assumed there were two.