I'm working on a nodejs project, I use request module to submit restful request and get response. (here is the module link: https://github.com/request/request)
Following the instruction, I should be able to get the response header by calling response.headers[''], however, seems it doesn't work, when I try to call var contentType = response.headers['Content-Type'], the contentType is undefined. (When I use postman, I could get Content-Type from the response). Anyone knows what's wrong?
This is the instruction from the site:
var request = require('request')
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
In node, the headers are accessed by using lowercased names, so using response.headers['content-encoding'] is correct.
Your code snippet currently works for me and displays 'server encoded the data as: gzip.'
Related
I am using superagent to make a request to Vimeo's Upload API.
My request looks as follows =
var request = require('superagent');
request
.post('https://api.vimeo.com/me/videos')
.set('Authorization', 'bearer ' + myAccessToken)
.set('Accept', 'application/vnd.vimeo.*+json;version=3.2')
.send({ type: "streaming" })
.end(function (error, response) {
//Code
}
I have to use the Accept header here to specify the version as mentioned in their documentation .
My problem is that the response.body is an empty object {}. The response.text is undefined - The response.status is 201.
I should get the response as shown in the documentation. But I get an empty object instead.
If I try the same request through POSTMAN, I get the response that I need. But using superagent I am not able to get it. Is there any additional configuration I need to do to get the response.body?
My client posted data from one website to my website using npm request module.
ie as follows.
testservice : function(req , res){
var data = { title : 'my title' , content : 'my content'};
request.post('https://dev.example.com/test' , data , function(err , response ,body){
if (err) console.log(err);
if(response) console.log('statuscode='+response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method , but i didnt get json data output.
Please help me out to get JSON data which is posted using request post method. Thanks.
Try this:
testservice: function(req, res) {
var data = { title: 'my title', content: 'my content' },
options = {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
};
request.post('https://dev.example.com/test', options, function(err, response, body) {
if (err) console.log(err);
if (response) console.log('statuscode=' + response.statuscode);
});
};
I tried to get the JSON data posted to my site from my client's site using request get method, but i didnt get json data output.
I believe you may be misunderstanding the request.get function. It doesn't "get" the data that was posted to your site, it in fact fires a "get" request off to a particular URL.
If you want to receive data on your site that was POST'ed, then you need to configure your server to listen for POST requests from your friends site and then parse out the posted data from the body of that request.
i.e. in your server code if you're using raw node.js
http.createServer(function(req,res){
if(req.method.toUpperCase() === "POST"){
//code to parse out the data from the post request
}
}).listen(8080)
For more detailed info on parsing out the POST'ed data, see How do you extract POST data in Node.js?
Let me know if this helps, please clarify your question if not.
I send it like so :
var url = "http://localhost:9001/v1/sanger/auth/facebook/callback",
options = {body: JSON.stringify(params), 'Content-type': 'application/json'};
request.post(url, options, function (error, response, body) {
... callbacks ...
});
I am not getting the params in the route (tried body, params and query)
When I use postman (http://cl.ly/image/473e2m173M2v) I get it in the req.body
A better way to do this (I'm assuming you've initialized your params variable somewhere else):
request = require('request');
var options = {
url: "http://localhost:9001/v1/sanger/auth/facebook/callback",
method: 'POST',
body: params,
json: true
};
request(options, function (error, response, body) {
... callbacks ...
});
You're not able to get the body because when you call JSON.stringify(params), you're converting params to a string and you don't have a json object anymore. If you send the information as plain/text but tell the request that you want json, your express app cannot verify the content-type, as could check with:
request.get('Content-Type'); // returns undefined
Since you want a json object, you shouldn't do this. Just pass the json object, like in the example above.
Then, in your route code, you can do both req.body or req.param('a_param') (for a especific key of your json) to get those values.
I am using html on client side and my server side code is on node.js. I have some url's defined in to the nodejs application and I am calling them from my client html file. From node I am calling my REST application which is at another server. This rest application is written in Jersey java web services. I am able to call node.js from my html and from node code I am getting response from Jersey web service module. After receiving this response I am setting it to response object of node.js but this response is not available on html jquery ajax call.
$.ajax({
type :"POST",
dataType: 'json',
data: jsontest,
url: 'http://<code>localhost</code>:9999/hello',
success: function(data) {
console.log('success');
console.log(data);
console.log(data.id);
}, error : function(response) {
console.log(JSON.stringify(response));
}
});
Server side code:
var tmp = req;
var authentication = JSON.stringify(tmp.body.authenticationKey);
console.log("authentication :- "+authentication);
requestObj({
url : "http://<code>restserver</code>:port/restmodule/controller/hello",
method : "POST",
headers : { "Content-Type" : "application/json","pubKey":authentication},
body : JSON.stringify(tmp.body)
},
function (error, res, body) {
indexresponseBody = JSON.stringify(JSON.parse(body).message);
}
);
res.writeHead(200, {'content-type':'text/html'});
console.log("JSON returned from REST "+indexresponseBody);
res.write(indexresponseBody);
res.end();
I am able to get the json and this is printed on node server console. But when I am writing this json to the response(res) object on firebug console I am not able to see this json. Can anybody tell me how can I get this response.
Could be because of async nature of callback, try this -
function (error, resp, body) {
indexresponseBody = JSON.stringify(JSON.parse(body).message);
res.writeHead(200, {'content-type':'text/html'});
console.log("JSON returned from REST "+indexresponseBody);
res.write(indexresponseBody);
res.end();
}
I'm writing a some node code, which to simulate a ASP.NET ajax client call. It is made as a http post request to the server, and I've managed to setup the request headers and body perfectly with the OS X tool CocoaRestClient. With this tool the server responds perfectly as expected.
When I try to do the same thing with Node.js, with the 'request' module, it fails:
My script:
var request = require('request');
request.post({
'uri': 'http://[The Url]/[The Service].asmx/[The Operation]',
'json': '{"callbackcontextkey":"[the context key]",[The set of json formatted key/value pairs] }',
'headers': { }
}, function(e, r, body) {
console.log("Response error: %j", e);
console.log("Response r: %j", r);
console.log("Response body: %j", body);
});
When I'm using the CocoaRestClient tool, all I specify is the Content-Type (application/json) parameter, and then just the request body as specified in the code (the 'json' attribute value).
My code makes the server side return this:
"There was an error processing the request."
And I can also see this in the response:
"jsonerror":"true"
What am I doing wrong? I consider using a network sniffing tool to see the differences...
The json param expects a JavaScript object and request turns it into a JSON string for you.
Try removing the quotes from around it like so:
var request = require('request');
request.post({
'uri': 'http://[The Url]/[The Service].asmx/[The Operation]',
'json': {"callbackcontextkey":"[the context key]",[The set of json formatted key/value pairs] },
'headers': { }
}, function(e, r, body) {
console.log("Response error: %j", e);
console.log("Response r: %j", r);
console.log("Response body: %j", body);
});
Alternatively, you could keep it as a string and set the body param instead of json and it would probably work that way too. More details here: https://npmjs.org/package/request