Purging Cloudflare cache with an API call in Node.js - javascript

I'm looking to purge Cloudflare's cache through its API. More specially, the purge all files command.
However, I keep running into the "Invalid Content-Type header, valid values are application/json,multipart/form-data" error message, despite explicitly setting the Content-Type header with Node.js' request package.
What am I missing?
var request = require('request');
gulp.task('cfPurge', function() {
var options = {
url: 'https://api.cloudflare.com/client/v4/zones/myZoneID/purge_cache',
headers: {
'X-Auth-Email': 'email',
'X-Auth-Key': 'myAPIkey',
'Content-Type': 'application/json'
},
form: {
'purge_everything': true,
}
};
function callback(error, response, body) {
var resp = JSON.parse(body);
if (!error & response.statusCode == 200) {
console.log('CF Purge: ', resp.success);
}
else {
console.log('Error: ', resp.errors);
for (var i = 0; i < resp.errors.length; i++)
console.log(' ', resp.errors[i]);
console.log('Message: ', resp.messages);
console.log('Result: ', resp.result);
}
}
return request.post(options, callback);
});
Output:
Error: [ { code: 6003,
message: 'Invalid request headers',
error_chain: [ [Object] ] } ]
{ code: 6003,
message: 'Invalid request headers',
error_chain:
[ { code: 6105,
message: 'Invalid Content-Type header, valid values are application/json,multipart/form-data' } ] }
Message: []
Result: null

According to the documentation for the cloudfare API, you need to send an HTTP DELETE request and not an HTTP POST request:
Modify the line...
return request.post(options, callback);
...with:
return request.del(options, callback);
Also, this is not a form. You need to put the JSON in the body of the data. So, replace the block...
form: {
'purge_everything': true,
}
...with:
body: JSON.stringify({'purge_everything': true})

Related

Why my NULL check is always failing in Node.js?

I am developing a REST API with AWS Lambda, API Gateway, and Node.js.
Here is my code:
const mysql = require('mysql2');
const PropertiesReader = require('properties-reader');
const prop = PropertiesReader('properties.properties');
const con = mysql.createConnection({
host : prop.get('server.host'),
user : prop.get("server.username"),
password : prop.get("server.password"),
port : prop.get("server.port"),
database : prop.get("server.dbname")
});
exports.getMilestoneStatusByID = (event, context, callback) => {
const { id } = event.queryStringParameters;
if(id==null)
{
var response = {
"statusCode": 404,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify("Missing Parameters"),
"isBase64Encoded": false
};
callback(null, response)
}
else{
console.log("id", id);
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from milestone_status where idmilestone_status = ?";
con.execute(sql, [id], function (err, result) {
if (err) throw err;
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(result),
"isBase64Encoded": false
};
callback(null, response)
});
}
};
In my code I am accepting a parameter called id, then get data from the database and return back as the response. If the id is not provided, i am sending an error response.
But, in any case the id is null or no parameter provided, then the user gets the standard AWS error output, "message": "Internal server error". In console, th But what I need is to pass 404 status code, with the message Missing Parameters.
e below error get printed.
Lambda returned empty body!
Invalid lambda response received: Invalid API Gateway Response Keys: {'trace', 'errorMessage', 'errorType'} in {'errorType': 'TypeError', 'errorMessage': "Cannot destructure property 'id' of 'event.queryStringParameters' as it is null.", 'trace': ["TypeError: Cannot destructure property 'id' of 'event.queryStringParameters' as it is null.", ' at Runtime.exports.getMilestoneStatusByID [as handler] (/var/task/source/milestone-status/milestonestatus-getbyid.js:17:11)', ' at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)']}
How can I implement null check and send the error that I am looking for?
The error says that event.queryStringParameters is undefined, not the .id in it. You can extend your check to also check for event.queryStringParameters, although you should check the documentation if that's even normal:
exports.getMilestoneStatusByID = (event, context, callback) => {
const params = event.queryStringParameters;
if (!params || params.id == null) {
var response = {
"statusCode": 404,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify("Missing Parameters"),
"isBase64Encoded": false
};
callback(null, response)
} else {
const { id } = params;
// ...
}

201 status node express API always failing

I am trying to make an api through express. However, the response from the server i am getting is 201 created. The HTTP request i am trying to make through promises is interpreting the then process as false and it continually goes through a failed criteria.
Any idea on how i can get 201 created through the example below.
Example: The output even while being successful automatically goes through error status.
router.get('/example', session, function (req, res) {
example(req.body, req.session.token).then(
(response) => {
res.json(response);
},
(err) => {
if (err.status) {
res.status(err.status).json({
status: err.status,
message: err.message
});
} else {
res.status(constants.HTTP_INTERNAL_SERVER_ERROR).json({
status: constants.HTTP_INTERNAL_SERVER_ERROR,
message: 'Internal Server Error'
});
}
}
);
});
module.exports.example = (body, token) => {
return new Promise((resolve, reject) => {
const mainToken = createRawToken(token);
request.post(
{
url: `${endpoint}`,
body: JSON.stringify(body),
headers: {
Authorization: mainToken,
"Content-Type": "application/json"
}
},
(error, response, bdy) => {
resolve(requestService.handleResponse(error, response, bdy, constants.HTTP_OK));
}
);
});
};
I think your problem is in the example function. The promise seems fine but i am assuming that you're naming your constants well.
constants.HTTP_OK should be constants.HTTP_CREATED. Behind them i am assuming that HTTP_OK is 200 and HTTP_CREATED should be 201.

Creating an Asana Task using a POST http request

I'm trying to use the asana-api to create a Task using a POST http request but I keep getting a 400 bad request as a response.
I managed to get data from the Asana-api using ( a GET request ), but I'm having trouble sending data to Asana with ( a POST request )
I'm using the 'request' module to do the api call
here's the error message :
`{"errors":[{
"message":"Could not parse request data,invalid JSON",
"help":"For more information on API status codes and how to handle them,
read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}
]}`
Here's my code:
testTask(){
var taskName = "Test Name for a Test Task"
var workspaceID = "123456789"
var projectID = "123456789"
var assigneeID = "123456789"
var parentID = null
this.createTask(taskName, workspaceID, projectID, assigneeID, parentID)
}
createTask(taskName, workspaceID, projectID, assigneeID, parentID){
var token = "0/1234abcd5678efgh9102ijk"
var bearerToken = "Bearer " + token
var task = {
data: {
assignee: "me",
notes: "test test test test",
workspace: workspaceID,
name: taskName,
projects: [projectID],
parent: parentID
}
}
var options = {
"method" : "POST",
"headers" : {"Authorization": bearerToken},
"contentType": "application/json",
"payload" : JSON.stringify(task)
}
try {
var url = "https://app.asana.com/api/1.0/tasks";
request.post(url, options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
}
catch (e) {
console.log(e);
}
}
I also tried a different implementation :
createTask(){
var token = "0/1234abcd5678efgh9102ijk"
var bearerToken = "Bearer " + token
var options = {
"method" : "POST",
"headers" : {"Authorization": bearerToken},
}
try {
request.post("https://app.asana.com/api/1.0/tasks?workspace=1234567&projects=765534432&parent=null&name=taskName&assignee=me", options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
}
catch (e) {
console.log(e);
}
}
Based on the examples provided by the request module, it appears that your options object uses payload as a key, but it should be body.

JSON Request works in Javascript but not in Nodejs (statusCode: 403)

I want to request a simple JSON File in NodeJS. With Javascript and jQuery it works like a charm:
$(document).ready(function() {
$.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) {
if (json["errorCode"] > 0) {
console.log("Offline");
$('#ampel').addClass('red');
} else {
console.log("Online");
$('#ampel').addClass('green');
}
});
})
But i can't get it to work with NodeJS:
var request = require('request');
var options = {
url: 'https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter',
headers: {
'content-type': 'application/javascript'
}
};
function callback(error, response, body) {
console.log(response.statusCode);
}
request(options, callback);
The StatusCode is always 403 and i can't work with the data. Can somebody help me, so i can get the same result like with jQuery?
Thanks!
I was able to find the solution with Mike McCaughan's help:
I had to send a different user-agent to get a 200 response. The code looks like this now:
var options = {
url: 'https://www.younow.com/php/api/broadcast/info/curId=0/user=',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
var str = JSON.parse(body);
if (str.errorCode > 0) {
...
} else {
...
}
}
request(options, callback);

JavaScript needle.put object not being parsed

Folks, trying to put the following object using the needle.js library:
var object = {
fName: 'Jasmine',
lName: 'Tests'
}
var options = {
json: true,
accept: 'application/json'
}
needle.put(url, object, options, function (err, resp, body) {
if (err) {
console.log ('post error',err);
callback (err, null);
} else {
console.log ("RETURNED", body)
callback (null, resp, body);
}
})
I get back:
RETURNED { code: 'InternalError', message: 'Unexpected token o' }
The Express API tries to do a JSON.parse() on an incoming request and fails. Any suggestions?
Thanks!

Categories

Resources