nodejs request target url - node.js

i want to get the result for this target url. by browser the result is ok, but this nodejs code don't work. i wish someone can help me,thanks a lot.
var request = require('request');
request = request.defaults({
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
}
});
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});

You can get the cookie from xueqiu.com homepage before hitting this URL. Cookies can be reused using a jar
var request = require('request');
request = request.defaults({
headers: {'Accept': '*/*',
'Content-Type': 'application/json'},
jar: true // reuse cookies across requests
});
request('http://xueqiu.com', function() {
request('http://xueqiu.com/stock/search.json?code=alibaba', function(error, res, body) {
if (error) {
console.log(error);
} else {
console.log(res);
}
});
});

Related

Error when sending https request to ROBLOX API

I'm writing a simple API request to Roblox so I can retrieve the X-CSRF-TOKEN to do POST requests. The issue I'm facing is "Error: socket hang up".
I tried to just run the link in my browser and it displays a JSON table, but when I do the request through node.js it errors out.
const https = require("https")
const options = {
hostname: "groups.roblox.com",
path: "/v1/groups/5307563",
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': '.ROBLOSECURITY=' + cookie
}
}
const request = https.request(options, res => {
res.on('data', data => {
console.log("data received")
})
});
request.on('error', error => {
console.log(error)
})
You need to end the request with request.end().
const https = require("https")
const options = {
hostname: "groups.roblox.com",
path: "/v1/groups/5307563",
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cookie': '.ROBLOSECURITY=' + cookie
}
}
const request = https.request(options, res => {
res.on('data', data => {
console.log("data received")
})
});
request.on('error', error => {
console.log(error)
})
request.end()

Node.js 3rd party REST API call

Im using nodejs to make a call to a 3rd party API. My code code returns the correct data for an id that I'm passing in my backend. When I run my app, to retrieve the data I go to localhost:5000/api/Dls.
My code
app.get("/api/Dls", (req, res) => {
const response = {
success: false
};
if (req.user && Authorized.myToken) {
response.success = true;
response.data = {};
response.data.user = req.user;
const id = response.data.user.sub;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + 'id',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Now I'm trying to do something like this localhost:5000/api/Dls/1234 instead of using a hard coded id in the backend
I attempted doing the following but when I enter a valid id in the url (ex. localhost:5000/api/Dls/1234) I get this "", any idea to what I should be doing?
app.get("/api/Dls/:id", (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/',
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const userDls = JSON.parse(data)
return res.json(userDls);
});
}
});
Any feedback would be appreciated!
You are not passing the route id to the api.
response.success = true;
var options = {
method: 'GET',
url: 'https://someApi/byId/' + req.params.id,
headers:{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
}
};

Why i am getting unable to open document error or blank pdf in opening a pdf on client side?

I am hitting a get api in react similar to http://www.orimi.com/pdf-test.pdf which needs some secret information which is available only at middleware written in node. I want to open the pdf on client side(browser). So I am hitting the proxy get api which will hit the middleware and middleware will hit the backend server, but I am getting unable to open document and blank pdf. Can anyone tell me what is wrong with this code?
fetch(pdfApiMiddlewareUrl, {
method: "GET",
headers: {
"Content-Type": "application/pdf",
'Content-Disposition': 'inline; filename=your_file_name'
},
responseType : 'blob'
})
.then(res => res.blob())
.then(response => {
var blobUrl = URL.createObjectURL(response);
window.open(blobUrl);
})
.catch(error => {
console.log("HEREEEEEEEE");
console.log(error);
});
MIDDLEWARE CODE:
var urlEndPointsToHit = decodeURIComponent(req.query.urlToHit);
var url = urlEndPointsToHit+'?secret='+secretInfo;
var options;
options = {
url: url,
method: 'GET',
headers: {
'Content-type': 'application/pdf'
},
};
if(options) {
options.qs = req.query || {};
}
request(options, function(err, resp, body) {
req.locals = body;
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Cache-Control', 'no-cache');
next();
});

POST Requests not working using request module in node.js

I want to send data to the java back end which is run on tomcat server.this is what i have tried so far.i have already installed request module.get method is working properly.
Router.post('/', function(req, res) {
request({
uri: "http://localhost:8080/HIS_API/rest/UserService/registerUser",
method: "POST",
form: {
roleId:2,
employeeId:26,
userName:"testing",
password:"123"
}
}, function(error, response, body) {
console.log(body);
});
});
You have to use JSON.stringify to send data like in this format. before that write console.log(error). and check what's the error you are getting.
request({
url: url, //URL to hit
method: 'post',
headers: { "Authorization": req.headers.authorization},//if required
timeout: 60 * 1000,
body: JSON.stringify(body)
}, function (error, result, body) {
if (error) {
console.log(error);
} else if (result.statusCode === 500) {
console.log('error');
} else {
console.log(body);
}
});

How to properly use putAsync

I searched here and there and ended up with no finding regarding putAsync method of promisified request by bluebird.
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: buApiUrl,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: BU,
workstations: formattedWorkStaions[BU]
})
}).spread(function (response, body) {
debugHelper.log(body);
}).catch(function (err) {
debugHelper.error(err);
});
Above is the code snippet that is in my program. And it does not send put request. While using postAsync, if will send post request successfully.
Your code seems fine to me.
Example
var request = require('request');
var Promise = require('bluebird');
Promise.promisifyAll(require("request"));
request.putAsync({
uri: 'https://httpbin.org/put',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
name: 'anon'
})
}).spread(function (response, body) {
console.log(body);
}).catch(function (err) {
console.error(err);
});
OR you can just pass JSON body like this -
request.putAsync({
uri: 'https://httpbin.org/put',
json: { name: 'anon' }
})
....
Make sure the API end-point is taking PUT requests and the variables BU,formattedWorkStaions[BU] are properly defined. I guess formattedWorkStaions should be formattedWorkStations?

Resources