Imgix Purge Post Request fails for unknown reason - node.js

I wanna purge an image from the imgix cache, they have a API for that (https://docs.imgix.com/setup/purging-images)
I use axios to make the request from my nodejs backend:
const imgixKey = functions.config().imgix.key;
const headers = {
Authorization: `Bearer ${imgixKey}`,
'Content-Type': 'application/json',
};
const data = JSON.stringify({
type: 'purges',
attributes: {
url: href,
source_id: 'SOsourceId',
},
});
try {
await axios.post('https://api.imgix.com/api/v1/purge', data, { headers });
functions.logger.log('Purged Image successfully' + href);
} catch (e) {
functions.logger.error('Error removing image from cache ' + href + ' -> ' + e);
}
Error removing image from cache {stackoverflowimgpath.png} -> Error: Request failed with status code 400
The problem is other than the status code 400 there is nothing else specified, I checked the image paths and tried different Content-Type headers like in their example but that also did not work.
Since I cannot get any more information out of the response I ask for help here since I do not know how to continue.

Checking imgix documentation, the body of your request should have a data property:
curl -X POST 'https://api.imgix.com/api/v1/purge' \
--header 'Authorization: Bearer <api-key>' \
--header 'Content-Type: application/vnd.api+json' \
--data-raw '{ "data": { "attributes": { "url": "<url-to-purge>" }, "type": "purges" } }'
So, just modify your message to (adding the data property to your json object):
const data = JSON.stringify({
data: {
type: 'purges',
attributes: {
url: href,
source_id: 'SOsourceId',
},
}
});

Related

getting 404, firebase + node.js, using "projects.locations.instances.create"

I'm trying to make an instance of a database with node.js in firebase realtime database.
My node.js route looks like this:
const axios = require('axios');
var {google} = require("googleapis");
var serviceAccount = require("paht/to/json");
router.post('/createnewdatabase', function (req, res) {
//scopes used for the create
var scopes = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/firebase"
];
// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
serviceAccount.client_email,
null,
serviceAccount.private_key,
scopes
);
// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
if (error) {
console.log("Error making request to generate access token:", error);
} else if (tokens.access_token === null) {
console.log("Provided service account does not have permission to generate access tokens");
} else {
var accessToken = tokens.access_token;
let apiKey = req.body.apiKey;
const config = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken
},
};
axios({
method: 'post',
url: 'https://firebasedatabase.googleapis.com/v1beta/projects/{project-id}/locations/europe-west1',
data: {
key: apiKey,
databaseId: 'segesggseg-656-sdgsdgs',
},
config
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
res.send('POST request to the homepage')
}
});
})
I'm getting a 404 when trying to call the route. I'm guessing it's something with the tokens. The documentation is here: https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create
I can't figure it out :-)
Please consider that according to the official documetation link:
"name field - Currently the only supported location is 'us-central1'."
I was able to create an instance using the api only with empty data parameter.
'https://firebasedatabase.googleapis.com/v1beta/projects/111111111111/locations/us-central1/instances?databaseId=myinstanceiddd&validateOnly=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{}' \
--compressed
200
{
"name": "projects/111111111111/locations/us-central1/instances/myinstanceiddd",
"project": "projects/111111111111",
"databaseUrl": "https://myinstanceiddd.firebaseio.com",
"type": "USER_DATABASE",
"state": "ACTIVE"
}
After answer above did not work for me... I was forced to read docs (https://firebase.google.com/docs/reference/rest/database/database-management/rest/v1beta/projects.locations.instances/create) word by word...
Second paragraph says that ur project needs to be on the Blaze plan in order to be able to create instance... After this doing this, it now works for me.

Polar accesslink API POST users not working

I'm currently trying to implement Polar accesslink API on an app, but when trying to POST a new user I still get this error:
url: 'https://www.polaraccesslink.com/v3/users/',
status: 400,
statusText: 'Bad Request',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
I already have the authorization token, which I know expires every 10min, and I'm using the service through a function that takes the token and the userID as parameters. This is my code:
postUser(memberId: string, token: string) {
const inputBody = { 'member-id': memberId };
const headers = {
'Content-Type': 'application/xml', 'Accept': 'application/json', 'Authorization': 'Bearer ' + token
};
const options = {
method: "POST",
headers: headers,
body: JSON.stringify(inputBody)
}
return new Promise<object>((resolve, reject) => {
fetch('https://www.polaraccesslink.com/v3/users', options)
.then(function(res: any) {
console.log(res)
return res.json();
}).then(function(body: any) {
console.log(body);
});
})
}
I'm implementing it the same way as it is specified in https://www.polar.com/accesslink-api/?javascript--nodejs#users but really don't know what might I be doing wrong. Thanks for helping me!.
I don't have experience with this specific API but i can see you send in the header Content-Type the value application/xml but the request body is JSON formatted.
Try send application/json in that header.
The Content-Type header is used in HTTP to specify the body mime type.
more info in: Content-Type HTTP Header - MDN
I also see this is the exact code in the sample but notice they have 2 sample requests and 2 sample results, one in XML and one in JSON each.
Any ideea why this POST gives 'invalid_Request'?
curl --location --request POST 'https://polarremote.com/v2/oauth2/token?grant_type=authorization_code&code=1f9edc0c5e60a0bab4fd3f1f00571a58' --header 'Authorization: Basic ... DA4OS05ZDc2LTJlNTQwZjFkZTc5ZA==' --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json'

Turning a CURL request into a Node js format with request-promise

I have been trying to convert a working POST CURL request into Node JS format that i can automate. Im reaching a wall with converting it and hoping someone can help.
Here is the curl:
curl -POST https://api-xxxxxxxx/add
-H "Authorization: Bearer xxxxxxx"
-H "Content-Type: multipart/mixed"
-F 'metadata={ "domain_id": 11661, "container_id": 18569512, "name": "TestFile", "size": "1072902", "originalfilename" : "xxx-d6", "mime": "x-html-package",
"attributes":"main_html_file_path=index.html\nduration=10000" }; type=application/json' -F "file=#xxx-d6.x-html-package"
Im using request-promise module to make this request but i might be making a mistake converting it.
let step1Options = {
method: 'POST',
uri: 'https://api-xxx/add',
form: {
metadata: {
domain_id: domainID,
container_id: 1856951,
name: "TestFileNodeJS",
size: "1072902",
originalfilename : "xxx-d6",
mime: "x-html-package",
attributes:"main_html_file_path=index.html\nduration=10000"
},
file: fs.createReadStream("xxx.x-html-package")
},
headers: {
"content-type": "multipart/mixed",
Authorization: "Bearer " + authID
}
};
rp(step1Options)
.then(function (body) {
console.log("success")
console.log(body)
})
.catch(function (err) {
console.log("Error: ", err)
// POST failed...
});
The error im getting:
body:
'{"error":"Unexpected Content-Type header: application/x-www-form-urlencoded. Expecting: multipart/mixed; boundary=<boundary>.","status":"error"}' } }
As far as i know, im changing the Content-Type but still thinks im not. Reading a bit of the documentation of Request-Promise, i dont believe multipart/mixed is a supported? Though i could be wrong.
Does anyone have an idea on how i can get this working or suggest alternatives?

Nodejs, http post json

Here is an example post that I want to do in my Nodejs server to get ClientID and secret.
Request example:
curl --request POST \
--url https://api.opskins.com/IOAuth/CreateClient/v1/ \
--header 'authorization: Basic {{AUTH_HASH}}' \
--data name=TestApp2 \
--data redirect_uri=http://localhost:1234
Response returns JSON structured like this:
{
"status": 1,
"time": 1535408581,
"response": {
"secret": "$nGwYVda##PErKAUpG#kHQ&YA1L)A*X1",
"client": {
"client_id": "ff371b045307",
"name": "TestApp2",
"redirect_uri": "http://localhost:1234",
"time_created": 1535407757,
"has_secret": true
}
}
I am trying with request :
const request = require('request');
var headers = {
'authorization': 'Basic ***my-api-key****'
};
var dataString = 'name=TestApp2&redirect_uri=http://localhost:5000';
var options = {
url: 'https://api.opskins.com/IOAuth/CreateClient/v1/',
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(body);
}
request(options, callback);
but getting error output like this :
{"status":401,"time":1540115259,"message":"API Key Required"}
I have been trying different codes and middlewares but couldn't make it. Also my test works perfect on Postman. I need help to post that and get my client_id and secret.
I found a way. It was really tricky for me. I needed to use my API Key and also client id.
Bellow codes worked. Thank you very much vitomadio !
I used reqclient from npm.
here is my code
var client = new RequestClient({
baseUrl:"https://api.opskins.com/IOAuth/CreateClient/",
debugRequest:true, debugResponse:true,
auth: {
user:"***My_apikey****",
}
});
var resp = client.post("v1/", {"name": "testApp2", "redirect_uri":"http://localhost:5000/"},{headers: {"authorization":"Basic **my_clientID"}}).then(response => {
// console.log(response);
});
also I am really curies and would like to know how can I do that with request.

How can I make this request in nodejs(status 415)?

I was using bash to do a task. And had some mess while trying to parse the response. Now I am using nodejs for the task. But I get following error:
"httpStatus" : 415,
"messages" : [ {
"errorCode" : "305",
"message" : "Unsupported media type 'application/x-www-form-urlencoded'"
} ]
This used to be my curl request in bash file:
curl --include\
--request POST \
--user "$USERNAME:$PASSWORD" \
--header "Content-Type: application/vnd.profitbricks.resource+json" \
--data-binary "{
\"properties\": {
\"name\": \"$servername\",
\"ram\": $RAM,
\"cores\": $CORES
}
}" \
https://api.profitbricks.com/rest/datacenters/$ID/servers ;
This is my current request:
var request = require('request');
var reqoptions = {
method: 'POST',
uri: 'https://api.profitbricks.com/rest/datacenters/'+options.vdcID+'/servers',
form:{
"properties":{
"cores": options.cores,
"ram": options.ramsize,
"name": options.servername
}
},
headers: {
'Authorization': 'Basic ' + new Buffer(options.user+':'+options.password).toString('base64'),
'Content-Type': 'application/vnd.profitbricks.resource+json'
}
};
request(reqoptions, function(err, res, body){});
form option changing content-type to form-urlencoded
you shouldn't use form in request options
send a binary data like here nodejs/express and binary data in POST
so use body: myBuffer instead of form: {...}
The problem was serialization. I stringified the object. Now it works.
var request = require('request');
var body = {
"properties":{
"cores": options.cores,
"ram": options.ramsize,
"name": options.servername
}
}
var reqoptions = {
method: 'POST',
uri: 'https://api.profitbricks.com/rest/datacenters/'+options.vdcID+'/servers',
body: JSON.stringify(body),
headers: {
'Authorization': 'Basic ' + new Buffer(options.user+':'+options.password).toString('base64'),
'Content-Type': 'application/vnd.profitbricks.resource+json'
}
};
request(reqoptions, function(err, res, body){});
This did the trick.

Resources