nodeJS request library: making POST request with surrogate key instead of URL - node.js

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)
}
})
}

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!

Unable to exchange code for access token in node.js. Mailchimp API

I am trying to use OAuth2 with the Mailchimp API, and I am following their documentation to the letter, but I am unable to complete step 4. At this step, I exchange the code I received from the authorization screen for the token. Per the documentation, this can be done in curl like so:
curl --request POST \
--url 'https://login.mailchimp.com/oauth2/token' \
--data "grant_type=authorization_code&client_id={client_id}&client_secret={client_secret}&redirect_uri={encoded_url}&code={code}" \
--include
I attempted to convert this to work on node.js by writing this:
var dataString = 'grant_type=authorization_code&client_id=' + clientid + '&client_secret=' + clientsecret + '&redirect_uri=' + encodedurl + '&code=' + url.parse(req.url, true).query.code;
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
data: dataString
};
function callback(error, response, body) {
if (!error) {
console.dir(JSON.stringify(body));
}
else{
console.dir(error);
}
}
request(options, callback);
When I make the request.debug = true, I see that I am getting a 400 error. The message sent to the console is a bunch of garbled characters though. When I use these same variables and endpoints to authenticate through Postman though, it works fine, so the issue is not with the variables or the API itself.
I am not entirely sure what I am doing wrong here. The request I am making seems almost identical what is written in curl in the documentation. So where am I going wrong?
Hmm, did you forget to define request?
var request = require("request");
Finally figured it out. The issue was in the header of the request. There are two ways to fix this. The first is to use "form" instead of "data". Request includes a "content-type: x-www-form-urlencoded" header automatically if the option "form" is used.
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
form: dataString
};
I am not sure what header is used when the "data" option is used, or if no content-type is declared at all. Either way, if you choose to continue to use the "data" option, you can manually declare a content-type header. This is the second possible solution.
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers:
{ 'Content-Type': 'application/x-www-form-urlencoded' },
body: dataString
};
After alot of tries, I figured out. You can use code only once. So make sure you use code you get from redirect URI only once.
With new code use this code
const dataString = "grant_type=authorization_code&client_id="+client_id+"&client_secret="+client_secret+"&redirect_uri="+redirect_uri+"&code="+req.body.code
var options = {
url: 'https://login.mailchimp.com/oauth2/token',
method: 'POST',
headers:
{
'Content-Type': 'application/x-www-form-urlencoded',
},
form: dataString
};
function callback(error, response, body) {
if (!error) {
let str = JSON.stringify(body)
res.setHeader("Content-Type", "application/json; charset=utf-8")
res.send(body)
}
else{
console.dir(error);
res.send(error)
}
}
request(options, callback);

make a GET request in node js equivalent to CURL request with -u parameter

i am trying to make a GET request to an external api from node js and express js.
I am using the request module to make the GET request-
in the options of the request -
const options = {
url: 'https://externalP_api_url/api/1/balance',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
I need to set the -u parameter as based on the example in the docs of the api. they used curl to make the request
curl -u keyid:keysecret https://externalP_api_url/api/1/balance
The problem is i cant set the -u keyid:keysecret in the options of my request i have tried putting it like a query string and in the header but i get a 401 and accoring to the api's docs that means the keyid:keysecret parameter is missing.
I have tried the curl and it works so i knw its not from the api's end and its not cause i am not sending from an https doamain because i would have a gotten a 403 response.
Take a look at https://curl.trillworks.com/#node
It typically does a pretty good job of pointing you in the right direction when converting curl to node.js. Based on your curl command, it is suggesting the following code:
var request = require('request');
var options = {
url: 'https://externalP_api_url/api/1/balance',
auth: {
'user': 'keyid',
'pass': 'keysecret'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
}
request(options, callback);

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