api call fails with request module in node.js app - node.js

The following API call fails for me when I try it in my app. It works fine from same machine in the browser. I should get a JSON response.
var url = 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC';
request.get({ url: url, json: json, strictSSL: false, headers: { 'User-Agent' : '' } }, function (err, resp, data) {
});
edit: by "fails" i mean i get a non-json error page.

You can't use an empty User-Agent header, otherwise the request fails.
So use something like:
'User-Agent' : 'request/x.y'

Related

node.js how to send multipart form data in post request

I am attempting to get data in the form of an image sent from elsewhere using multipartform, however when trying to understand this via the great sanctuary(stack overflow) there are missing elements I don't quite understand.
const options = {
method: "POST",
url: "https://api.LINK.com/file",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
formData : {
"image" : fs.createReadStream("./images/scr1.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});
2 questions:
what is the variable auth, what do I initialize it to/where/how do I declare it
what is the url "api.LINK.com", is this just the site url where this code is on
After your comments I think I may be doing this wrong. The goal is to send data(an image) from somewhere else(like another website) to this node app, then the nodeapp uses the image and sends something back.
So that I would be the one creating the API endpoint

i get an unexpected token error when I do post request with json

I am trying to do a post request with json in a format where I use the option={method, uri, ...} instead of request.get(... because I want to convert this into a function where method, uri, body are the parameters
Im calling this request in node.js to a foreign service. Simple GET requests to that foreign service worked fine. (By the way I did test if it works via postman)
below is the code where i do the request. I have tried without json:true and instead of body, I tried json:{"prod...
request({
headers: {
"Content-type":"application/json;charset=UTF-8",
"Authorization":signature
},
method:'POST',
uri: PATH+`openapi/apis/api/v1/categorization/predict`,
json:true,
body:{"productName": "readymix"}
}, (err, res, body) => {
if(err) console.log(err);
else console.log(body);
})
I keep getting the following error: Unexpected token o in JSON at position 1 The format looks all correct, I dont know why its not working
=====Problem solved=====
removing json:true and fixing body:{"productName": "readymix"} to body:JSON.stringify({"productName": "readymix"}) fixed the problem!

request.get vs CURL in NodeJS

I have an URL mapped as
router.route('/user').get(policies.isAuthenticated, policies.isCurrentUser, userController.get);
When I access the URL with CURL or from the browser it runs through all of the chained methods. But when I access it from NodeJS it only runs the last method, userController.get. I'm using the following request method.
request.get({
url: testURL,
body: user.id,
json: true
}, function(err, res: express.Request) { ... });
Do I need to include some options in request.get so that it acts like a 'proper' request?

Referrer header not found error while calling http requests from node.js

I am getting the error "message": "Referrer header not found while calling the http request from the node.js server.
The requirement is like, first I need to hit a box which accepts only the ajax requests and then route to the actual service.
Snapshot of the code
var options = {
url: 'http://' + fullpath,
qs : params,
headers : {
Cookie : "COOKIE=" + my_cookie,
Origin: 'http://my_url',
"X-Requested-With": 'XMLHttpRequest'
},
encoding : null,
};
request.get(options, function (err, response, body) {
}
Any thoughts on the above error ?
Thnx
You're not passing a Referer header to request.get and apparently the server at http://[fullpath] expects it (perhaps as a sort of misguided form of security).
Try adding one:
headers : {
Cookie : "COOKIE=" + my_cookie,
Origin: 'http://my_url',
"X-Requested-With": 'XMLHttpRequest',
Referer : 'http://' + fullpath
},

POSTing to a basic access authorization protected resource

I am experiencing a problem while POSTing to a resource which is protected by basic access authentication.
Here is the code, I am using #mikeal's request:
request.post({
uri: "http://user:password#mysite.com/resource",
json: {
"id": "1",
"par1": "a",
"par2": "b"
}
}, function (error, response, body) {
console.log(error);
console.log(response);
console.log(body);
});
I have { [Error: Parse Error] bytesParsed: 0 } in error and undefined in both response and body. If I remove the "user:password" part I correctly get a 401 HTTP Basic: Access denied.
Do you know if there's a way to POST JSON to a protected resource like in my case? If not, I believe I'll have to go the http module way, but I'm leaving that as a final resource since it's a lot more verbose.
UPDATE: To have this as simple as possible I've moved this file in a new directory and did a npm install request. The problem went away, I checked from where the byteParsed come from and found it's in "formidable" which is required by express, which I had in the directory where I was running this test. A bit confused right now.
I did it like this:
var options = {
method: 'POST',
uri: 'http://your.url.com/',
form: {
field1: 'somevalue',
field2: 666.66
},
headers: {
'Authorization': 'Basic ' + new Buffer("username:password").toString('base64')
}
};
request(options, function(error, response, body) {
// do stuff
});
You must add an header to your request with this rules:
http://en.wikipedia.org/wiki/Basic_access_authentication
Basically you must encode the string: username:password in base64 and add encoded string in an http header:
Authorization: Basic "Base64(username:password)"
I don't know if is possible add header with jquery or javascript. Sorry.
Look here: http://api.jquery.com/extending-ajax/#Transports

Resources