I am currently trying to establish a connection with an external API that has specific specifications:
Host: name.of.host
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Through the utilization of the request
module from npm
, I am constructing the POST request in the following manner:
function post2(uri, headerObj, bodyObj, bodyStr) {
console.log("Sending a post request to " + uri + " . . .");
var options = {
uri: uri,
form: bodyObj,
qs: bodyObj,
method: 'POST',
json: false,
headers: headerObj
};
request(options, function(error, response) {
console.log(JSON.stringify(response));
console.log(error, response.body);
return;
});
}
The setup for the header and body objects is as follows:
var headerObj = {
'Host': 'name.of.host',
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
};
var bodyObj = {
'client-id': 'GUID',
'grant_type': 'refresh_token',
'refresh_token': 'alphanumeric data containing / = and + characters'
};
I have verified that the client-id
and refresh_token
values are correct. Furthermore, I have tested the request using the same information on Postman without encountering any problems. However, despite these validations, I continue to receive the following error message from the API:
null '{"error":"invalid_client"}'
I have consulted the documentation available at this link related to the request
npm module and adhered to the request(options, callback) approach since it appears that request.post
does not support custom headers. What could be the issue here?
-- UPDATE --
In an attempt to address the situation, I switched to using XMLHttpRequest and applied the exact same set of headers. Initially, I encountered a
Refused to set unsafe header "Host"
error which prompted me to eliminate the Host header. However, even after this modification, there were no errors reported but there was also no response displayed in the command prompt (I am utilizing node for deployment).
This is the code snippet I implemented:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open("POST", '/connect/token', true);
//Include necessary headers with the request
xhr.setRequestHeader("Host", "name.of.host");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.onreadystatechange = function() { // Execute when the state changes.
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
// Request completed successfully. Perform processing here.
console.log(xhr.responseText);
}
}
xhr.send("client-id=guid&grant_type=refresh_token&refresh_token=tokenstuff");
I cannot seem to pinpoint the root cause of this issue. While there are no outgoing requests visible in the browser, logs from the node command line demonstrate that attempts are being made.