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
Related
I am trying to use nodeJS request library to issue a POST request to purge content associated with a certain surrogate key via Fastly API. The POST request would look something like this:
POST /service/SU1Z0isxPaozGVKXdv0eY/purge
Content-Type: application/json
Accept: application/json
Fastly-Key: YOUR_FASTLY_TOKEN
Fastly-Soft-Purge: 1
Surrogate-Key: key_1 key_2 key_3
I tried to do this in node.JS two different ways.
The first:
// perform request to purge
request({
method: `POST`,
url: `/service/${fastly_service_id}/purge${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
// url was not valid to purge
if (err) {
console.log("is there an err???")
console.log(err)
}
})
}
I get, Error: Invalid URI: /service/<fastly_Service_id>/purge/<surrogate_key>
I double checked my surrogate key via curl -s -I -H "Fastly-Debug: 1" <URL corresponding to surrogate key> | grep surrogate-key
And it returns the same surrogate-key used in my code.
In the second attempt, I tried:
// perform request to purge
request({
method: `POST /service/${fastly_service_id}/purge${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
// url was not valid to purge
if (err) {
console.log("is there an err???")
console.log(err)
}
})
}
I get the error, Error: options.uri is a required argument
I'm unfamiliar with node and the code involved to make a HTTP request successfully, but from what I can see of the code you have provided it would appear the error is related to the fact you've not provided a fully qualified domain (e.g. you're missing https://api.fastly.com before the path).
Unless of course this is configured elsewhere in your code and it's just not visible here.
Also make sure that inbetween /purge and ${surrogateKeyArray[i]} you include a / divider (I show this in my example code below).
So with this in mind I would suggest trying:
request({
method: `POST`,
url: `https://api.fastly.com/service/${fastly_service_id}/purge/${surrogateKeyArray[i]}`,
headers: headers,
}, function(err, response, body) {
if (err) {
console.log(err)
}
})
}
What I'm trying to do is use the OctoPrint Rest API. I keep running into an error though when I'm trying to do POST requests that require a command. Here's an example of that in the docs.
POST /api/connection HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "connect",
"port": "/dev/ttyACM0",
"baudrate": 115200,
"printerProfile": "my_printer_profile",
"save": true,
"autoconnect": true
}
What I'm most confused about is where I include the command or the port values. Here's what I'm currently doing.
var self = this;
request({
url: OCTOIP + "/api/connection",
method: "POST",
"content-type": "application/json",
headers: {
"X-Api-Key": KEY
},
body: JSON.stringify({"command": "connect"})
}, function(error, response, body) {
//var info = JSON.parse(body);
if (error) {
console.log(error);
self.tell("Could Not Connect");
}
else {
console.log(body);
self.tell("Connected to printer.");
}
});
What happens is I keep getting this error message.
Expected content-type JSON
I've tried changing content-type to just json, I've tried getting rid of the JSON.stringify and just putting it as {"command": "connect"}. Or even dropping the curly brackets altogether. Another thing I tried was using form and instead of the body. None of those have worked. What am I doing wrong here?
Fixed the issue. It turns out it wasn't working because I didn't put the content-type in the header.
I'm trying to hit one of the mailchimp's api, but for somehow I always get
{
"type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title": "Resource Not Found",
"status": 404,
"detail": "The requested resource could not be found.",
"instance": ""
}
I'm using request library to make the request and see the code below
var uniqueListId = "XXXX";
var apiKey = "XXX";
.post(function(req, res) {
var email = req.body.email;
var status = "subscribed";
request({
url: 'https://usX.api.mailchimp.com/3.0/lists/' + uniqueListId + '/members',
headers: {
'Authorization': 'randomUser ' + apiKey,
'Content-Type': 'application/json',
},
method: 'POST',
json: {
email_address: email,
status: status
}
}, function(err, response, body) {
if (err) {
res.json(err);
} else {
res.json(response.statusCode, body);
}
});
});
For the sake of clarity, this is the documentation that I'm referring to http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
Is it because of my req.body data?
I agree with #TooMuchPete, The same issue happened with me and scratched my head for a whole day to solve that issue, and finally, I've found that Audience Idlist_id is wrong.
we need to pick the one which is located under the AudienceTab > ViewContacts > Settings > Audience and Defaults > Audience ID, but unfortunately, I have picked the one which is showing in the URL.
If you're getting a 404 it's because the URL you're hitting doesn't refer to an actual resource. Probably uniqueListId is either empty or not the right ID.
I would suggest using the Postman chrome add-on app to play with the requests and posts - you could also use it to generate sample code, in most languages. It is great for debugging.
After using it, I found that your request options should look something like:
let requestOptions = {
hostname: 'us14.api.mailchimp.com',
method: 'GET',
path: '/3.0/lists' + listId,
headers: {
'Authorization': 'User ' + config.mailChimp.apiKey,
'Content-Type': 'application/json',
},
}
You're almost certainly confusing mailchimp's web_id with list_id. The list_id is the one you need for the API, the web_id is the one you see in the url when you open your list.
I have absolutely no idea why mailchimp uses 2 different ids, nor why they don't seem to put it forward in any of their developer documentation.
Below is an article which explains how to find it - basically you go to your list -> settings tab -> list name and defaults.
https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6
I'm trying to send bath request to GMail API using request for nodejs. The problem is even trough I generate the same query as in documentation, gmail always respond with 400 BadRequest
Those are my headers in form of json
{ 'Content-Type': 'multipart/mixed; boundary=c2db2692-8877-4159-bf02-03e6c5d3ffbf',
authorization: 'Bearer MY_TOKEN',
'content-length': 231 }
Example of body content
--c2db2692-8877-4159-bf02-03e6c5d3ffbf
Content-Type: application/http
Content-ID: <item1:12930812#barnyard.example.com>
GET /gmail/v1/users/sneg0k32#gmail.com/messages/14c6c0c43e9bb16b
--c2db2692-8877-4159-bf02-03e6c5d3ffbf--
Any suggestions why this happens? Request generates extra few spaces and make headers in lowercase, however I'm not sure if this is the problem.
Example of nodejs code
request({
method: 'POST',
uri: 'https://www.googleapis.com/batch',
auth: {
bearer: key
},
headers: {
'Content-Type': 'multipart/mixed'
},
multipart: _.map(queries, function(query) {
return {
'Content-Type': 'application/http',
'Content-ID': "<item1:12930812#barnyard.example.com>",
body: 'GET ' + query
}
})
}, function(error, response, body) {
console.log(response.request.headers)
_.map(response.request.body, function(chunk) {
console.log(chunk.toString())
})
console.log(body)
})
UPD: This is clearly an issue with how I make my node call, send same request via HTTPTester and everything worked fine
UPD2: Decided to use bachelor, however I haven't figured what was causing this issue with plain request
Quite hard to troubleshoot such a problem. I would more than likely say it's down to the spaces. I had a similar issue that was because the request body was seen as invalid due to it's structure.
Uppercase or lowercase headers shouldn't cause an issue.
If it helps I've created a node module to creating batch requests: https://www.npmjs.com/package/batchelor. Feel free to use it.
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'