Node js Request - Empty body in response - node.js

I am using node js request to retrieve the HTML from the following URL but the body is returning empty.
var request = require("request");
var url = 'http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20';
request({
uri: url
}, function (error, response, body) {
console.log(body);
if (response.statusCode != '200') {
console.log('fail');
console.log(response.statusCode + ' # ' + error);
} else {
console.log(response.statusCode);
console.log('############');
console.log(response);
}
});
On closer inspection I can see this in the response:
_header: 'GET /webapp/wcs/stores/servlet/CatalogNavigationSearchResultCmd?langId=-1&storeId=12556&catalogId=33057&beginIndex=1&viewAllFlag=false&pageSize=20&searchTermScope=3&searchTermOperator=LIKE&searchType=ALL&sort_field=Relevance&searchTerm=TS19M11KRED&x=25&y=11&geoip=search HTTP/1.1\r\nreferer: http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20&geoip=prod\r\nhost: www.topshop.com\r\nConnection: close\r\n\r\n',
_headers:
{ referer: 'http://www.topshop.com/en/tsuk/product/bags-accessories-1702216/scarves-465/feather-wings-5884878?bi=0&ps=20&geoip=prod',
host: 'www.topshop.com' },
Which I assume means that there has been a redirect? Even though its returned a 200 OK instead of a 302 redirect.
I'm not sure of the best way to retrieve the body from the redirect? Do I need to make another request to the URL in the header? But shouldn't the response code be a 302 in this case instead of a 200?
Any help appreciated.

What you show seem like something that happened after a redirect - see that the referer is set to your original URL.
Maybe you should set more headers, like User-Agent because some servers don't respond without it.
For example, see the code that I wrote for this answer:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
It returns:
https://github.com/rsp
Note that it doesn't work without the User-Agent header:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
It returns:
Status: 403
The same URL, the same code - the only difference is the User-Agent header.

Related

trouble with parsing in JSON

i am trying to run this code but it keeps giving me a ReferenceError: json is not defined. Am I putting the JSON parse in the wrong position or something? This is basically a scraper, so it returns a lot of information and that is why it needs to be parsed
const request = require('request');
const options = {
method: 'GET',
url: 'https://siteToParse.com/api/v1/timelines/public',
json: true,
};
obj = JSON.parse(json);
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
});
EDIT: I changed it to obj = JSON.parse(JSON.stringify(body)) and it didn't throw any errors at all. But it's still returned a lot of information, and I'm not sure what to do with it?
I think you should rewrite it as this:
const request = require('request');
const options = {
method: 'GET',
url: 'https://siteToParse.com/api/v1/timelines/public',
json: true,
};
request(options, function(err, res, body) {
if (err) {
console.dir(err);
return;
}
console.log('headers', res.headers);
console.log('status code', res.statusCode);
console.log(body);
obj = JSON.parse(body); //---------------------> call to parse should come here
console.log(obj);
});

Post request to external api

after a post request from an ajax call in angularjs, i want to send the request params from angularjs to an external api. I get all params i want. But I don't know, how i can make a new post request to the api, inside my nodejs url. I need this step to nodejs.
This is my Code
router.post({
url: '/user/:id/sw'
}, (req, res, next) => {
var userId = req.pramas.id;
var firstName = req.pramas.firstName;
var lastName = req.pramas.lastName;
var data = 'test';
res.send(200, data);
});
I found some solutions like this on: (just example code)
request({
uri: 'http://www.giantbomb.com/api/search',
qs: {
api_key: '123456',
query: 'World of Warcraft: Legion'
},
function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(body);
} else {
res.json(error);
}
}
});
but this doesn't work. How I can make a new Post Request with the req.params to an external api? Also i need a Response from the api..
Thanks for help and Ideas :)
Its req.params not req.pramas
Try this
var request = require('request');
router.post({
url: '/user/:userId/shopware'
}, (req, res, next) => {
var params = req.params;
request.get({
uri: 'http://www.giantbomb.com/api/search',
qs: params // Send data which is require
}, function (error, response, body) {
console.log(body);
});
});
Try this,
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'http://localhost.com/test-url',
body: {
foo: 'bar'
},
json: true
// JSON stringifies the body automatically
};
​
request(options)
.then(function (response) {
// Handle the response
})
.catch(function (err) {
// Deal with the error
})
var request = require("request");
exports.checkstatus = async (req, res) => { //this is function line you can remove it
try {
var options = {
method: 'POST',
url: 'https://mydoamin/api/order/status',
headers:
{
signature: '3WHwQeBHlzOZiEpK4yN8CD',
'Content-Type': 'application/json'
},
body:
{
NAME: 'Vedant',
ORDERID: 'ORDER_ID1596134490073',
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body); //get your response here
});
} catch (error) {
return fail(res, error.message);
}
};

How do i send data to outside from nodeJS?

I have a need to send data from my NodeJS server to an outside server. I have tried many codes and searched for this alot, but not getting any proper working example or its not working in my case.
Here is my code:
app.get('/getFrom', function (req, res) {
var request = require('request');
// Try 1 - Fail
/*var options = {
url: 'http://example.com/synch.php',
'method': 'POST',
'body': {"nodeParam":"working"}
};
request(options, callback);
*/
// Try 2 - Fail
/* request({
// HTTP Archive Request Object
har: {
url: 'http://example.com/synch.php',
method: 'POST',
postData: {
params: [
{
nodeParam: 'working'
}
]
}
}
},callback)*/
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("body " + body); // Show the HTML for the Google homepage.
res.send(body);
}
else{
console.log("Error " + error);
res.send(error);
}
}
/* ------ HTTP ------ */
var postData = querystring.stringify({
'nodeParam' : 'Hello World!'
});
// try 3 - Fail
/*var optionsHTTP = {
hostname: 'http://example.com',
port: 80,
path: '/synch.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req1 = http.request(optionsHTTP, function(res1){
console.log('STATUS: ' + res1.statusCode);
console.log('HEADERS: ' + JSON.stringify(res1.headers));
res1.setEncoding('utf8');
res1.on('data', function(chunk){
console.log('BODY: ' + chunk);
});
res1.on('end', function(){
console.log('No more data in response.')
})
});
req1.on('error',function(e){
console.log('problem with request:' + e.message);
});
// write data to request body
req1.write(postData);
req1.end();*/
/* ------ /HTTP ------ */
Please let me know where I am wrong
Not sure why exactly your request might be failing, but this is a simple and straightforward sample on using the request module in npm:
var request = require('request');
var postData = {
name: 'test123'
}
request({
url: 'http://jsonplaceholder.typicode.com/posts',
method: 'POST',
data: JSON.stringify(postData)
}, function(err, response) {
if (err) {
return console.error(err);
};
console.log(JSON.stringify(response));
})
This snippet makes a request to a rest API and display the result on the console. The response data is available in the response.body property.
I found a working and tested solution :
request({
url: 'http://example.com/synch.php', //URL to hit
qs: {nodeParam: 'blog example', xml: xmlData}, //Query string data
method: 'POST', //Specify the method
},callback);

NodeJS/Express, Receiving pdf in response body

I have a node instance using express. It makes call to a JAVA backend. When I receive the response I check if there is a content-disposition header and react accordingly with the type of file.
The content of the response.body is the pdf in binary content. With content-type header "application/pdf;charset=UTF-8". I also receive a Content-Transfer-Encoding header set to binary.
If I call my JAVA backend directly from a REST client, everything is fine and I can view the raw body or download the file.
If I go with node, the PDF is blank. But has the correct number of pages.
Here's how I forward the respond to the frontend.
res.status(response.statusCode).set('content-disposition', response.contentDisposition).set('Content-Type', response.contentType).send(response.body);
Is it possible Express is converting it to some default encoding before I can even have access to the response ?
All I want to do is take the body response from my java backend ajust the headers and send it back to the frontend.
Thank you
EDIT
This is the options I pass to my request function
method=GET, user=username, pass=password, uri=http://appsjava-veo01.hostname:8081/VEO/r/pap/pap5001/produire/311, Content-Type=*/*, Accept=*/*
Calling my http handler, and in the callback sending back the response
httpRequest(options, req, res, function(err, response){
if (err){
return next(err);
}else{
if (response.jsonResponse){
res.status(response.statusCode).set('Content-Type', 'application/json').send(response.jsonResponse);
}else{
if (response.contentDisposition){
res.status(response.statusCode).set('Content-Disposition', response.contentDisposition).set('Content-Type', response.contentType).send(response.messageHtml);
}else {
res.status(response.statusCode).set('Content-Type', 'application/json').send(JSON.stringify({
success: response.success,
message: response.message,
messageHtml: response.messageHtml,
dateJour: response.dateJour,
usager: response.usager
}));
}
}
}
});
var httpRequest = function(options, req, res, callback) {
var errorMsg, dateJour;
ASQ(function (done) {
request(options, function (error, response) {
if (!response) {
done.fail(error);
} else {
done(response);
}
});
})
.then(function (done, response) {
var bodyResponse,
httpResponse,
jsonResponse,
contentDisposition = response.headers['content-disposition'],
usager = (req.session.cas) ? req.session.cas.user : 'nocas';
dateJour = new Date().toJSON();
//Validation et aiguillage selon les status code http
if (response.statusCode === 401) {
req.session.pt = '';
httpResponse = {
'statusCode': 401,
'success': false,
'message': '401 - Authorization requise',
'messageHtml': response.body,
'dateJour': dateJour,
'jsonResponse': null,
'usager': usager
};
return callback(null, httpResponse);
} else if (response.statusCode.toString().charAt(0) === '2' || response.statusCode === 406 || response.statusCode === 428) {
if (contentDisposition) {
var contentType = utils.extractContentType(contentDisposition);
httpResponse = {
'statusCode': response.statusCode,
'success': true,
'message': 'Téléchargement du fichier',
'messageHtml': response.body,
'dateJour': dateJour,
'jsonResponse': null,
'contentDisposition': contentDisposition,
'contentType': contentType,
'usager': usager
};
return callback(null, httpResponse);
...................

Slack no payload received nodejs

SO using curl I can successfully send post request to slack
curl -X POST --data-urlencode 'payload={"channel": "#tech-experiment", "username": "at-bot", "text": "This is posted to #general and comes from a bot named webhookbot.", "icon_emoji": ":ghost:"}' https:/company.slack.com/services/hooks/incoming-webhook?token=dddddddd2342343
however when I converted it to code using nodejs
var request = require('request');
var http = require('http');
var server = http.createServer(function(req, response){
response.writeHead(200,{"Content-Type":"text/plain"});
response.end("end");
});
option = {
url: 'https://company.slack.com/services/hooks/incoming-webhook?token=13123213asdfda',
payload: '{"text": "This is a line of text in a channel.\nAnd this is another line of text."}'
}
request.post(
option,
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}else {
console.log('wtf')
console.log(response.statusCode)
console.log(response)
console.log(error)
}
}
);
it throws status 500. can anyone help?
i reviewed the token
also done my research but nothing is working..
I appreciate all your help
You need to use the https library, since the server requests are on a different port. You current code is sending the request to port 80 instead of port 443. This is some sample code I built for an integration.
var https = require( 'https' );
var options = {
hostname : 'company.slack.com' ,
path : '/services/hooks/incoming-webhook?token=rUSX9IyyYiQmotgimcMr4uK8' ,
method : 'POST'
};
var payload1 = {
"channel" : "test" ,
"username" : "masterbot" ,
"text" : "Testing the Slack API!" ,
"icon_emoji" : ":ghost:"
};
var req = https.request( options , function (res , b , c) {
res.setEncoding( 'utf8' );
res.on( 'data' , function (chunk) {
} );
} );
req.on( 'error' , function (e) {
console.log( 'problem with request: ' + e.message );
} );
req.write( JSON.stringify( payload1 ) );
req.end();
I think it is not payload but form.
This code succeed in calling Incoming Webhooks.
var request = require('request');
var options = {
uri: "https://hooks.slack.com/services/yourURI",
form: '{"text": "This code..."}'
};
request.post(options, function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body.name);
} else {
console.log('error: '+ response.statusCode + body);
}
});
wanted to chime in, as I found this while also trying to do the same thing. I ended up doing this:
got('https://hooks.slack.com/services/[your configured url]', {
method: 'POST',
body: JSON.stringify({
"text": "message" + variable
})
});
Either use form in your option object or set a body parameter along with the 'content-type' set to 'application/x-www-form-urlencoded'. Here's a working example.
var payload = JSON.stringify(payload)
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'Your Webhook URL',
body: "payload="+payload
}, function(error, response, body){
if(error){
console.log(error);
}
console.log(body);
});

Resources