I'm trying to make a XMLHttpRequest to a server, the server accepts JSON as arguments and it's supposed to register the arguments I'm sending.
Here's my code:
function makeXMLRequest() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://mywebserverhere/register", true);
xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlhttp.setRequestHeader("Access-Control-Allow-Methods", "POST, GET");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status != 200) {
// Error
return;
}
alert(xmlhttp.responseText);
}
xmlhttp.send({"name": "pedro21", "pass": "nAosei1"});
}
But I get this error:
XMLHttpRequest cannot load http://mywebserverhere/register. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
Any ideas?
To allow CORS in a POST request you need to make a header. With GET you don't must to put this, but with POST you need:
xmlhttp.setRequestHeader('X-PINGOTHER', 'pingpong');
Related
I'm trying to use an HTTP request in JavaScript to retrieve a file from the Slack API. I managed to get the url_private_download of the file, but if I try to make an HTTP GET request using that URL, I get an error in the console saying that: Failed to load url_private_download: Response for preflight is invalid (redirect).
Here's my code:
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
}
};
xmlHttp.open("GET", url_private_download, true);
xmlHttp.setRequestHeader("Authorization", "Bearer " + my_slack_token);
xmlHttp.setRequestHeader('Access-Control-Allow-Headers','*')
xmlHttp.send(null);
I am trying to develop a browser extension that will help people to some stuff way easier.
One of the things that I need to do is sending couple of http requests.
I need to recreate requests that site makes when doing certain things.
Now site uses Request Payload which is my first time using(used form data),therefore I don't know how to make Request Payload same as when site sends request.
var request = new XMLHttpRequest(),
url = 'https://www.hidden.com/api/v1/tipuser/',
data = 'steam_64=76561198364912967&tip_asset_ids=[]&tip_balance=0',
token ='...';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'text/plain');
request.setRequestHeader('authorization', token);
request.send(data);
This is my code and after sending it you can see how my Request Payload looks.
I have been having difficulties for days now and I searched online but couldn't find solution to this.I know that I just have to write it differently .
This is site's request
This is my request
Cheers!
Could you try sending your request as application/json and build your data object like in the example below?
Your Content-type request header should be application/json
var request = new XMLHttpRequest(),
url = 'https://jsonplaceholder.typicode.com/posts/',
data = {
steam_64: '76561198364912967',
tip_asset_ids: [],
tip_balance: 0,
token: '',
};
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("The request and response was successful!");
}
};
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json');
request.setRequestHeader('authorization', data.token);
request.send(JSON.stringify(data));
I followed this article to connect to Azure via Rest where the first step is to get an access-token for the service. So i tried to send the following request:
POST https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: wamsprodglobal001acs.accesscontrol.windows.net
Content-Length: 120
Expect: 100-continue
Connection: Keep-Alive
Accept: application/json
grant_type=client_credentials&client_id=ams_account_name&client_secret=URL_encoded_ams_account_key&scope=urn%3aWindowsAzureMediaServices
and replaced the client_id and key(encoded) in the data to be posted.
But Chrome promptly complains about setting the unsafe Host-, Content-Length-, Connection- and Expect-Headers. So i omitted those and end up with the following:
xhr = new XMLHttpRequest();
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json");
xhr.send("grant_type=client_credentials&client_id=<id>&client_secret=<encodedSecret>scope=urn%3aWindowsAzureMediaServices");
now upon sending the request i get:
XMLHttpRequest cannot load https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://nope.com' is therefore not allowed access.
But the request works when i send it through the Rest Client, Fiddler and requestmaker.com which i take as evidence that the request is formed correctly ...
Any hint as to how i can get this to work would be greatly appreciated.
Try the following (generated from POSTMAN)
var data = "grant_type=client_credentials&client_id=<ACOUNTNAME>&client_secret=<ACCOUNTKEY>&scope=urn%3AWindowsAzureMediaServices";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("host", "wamsprodglobal001acs.accesscontrol.windows.net");
xhr.setRequestHeader("connection", "Keep-Alive");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
In Postman, i have to have the Interceptor plugin enabled for this to work though, and disable Automatically Follow Redirects. See if that helps at all.
After you get the response back and parsed the access_token, you can use it in the next call to get the closest API endpoint like this
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://media.windows.net/");
xhr.setRequestHeader("x-ms-version", "2.11");
xhr.setRequestHeader("authorization", "Bearer <ACCESS_TOKEN>");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
The title explains my problem clearly. I am testing the AJAX requests of my application but I cannot send some headers, for example Authorization header.
For testing I use this endpoint to echo me the headers I sent. Here is my javascript code:
var loadDoc = function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
console.log(JSON.parse(this.responseText));
};
}
xhttp.open("GET", "http://headers.jsontest.com/", true);
xhttp.setRequestHeader("Authorization", "JWT token");
xhttp.send();
}
I can send the exact same request with python's requests module. But I can't send it with XMLHttpRequest. XMLHttpRequest can send the Content-Type header and the server echoes me the headers but not Authorization.
What is going on here?
I have a simple request I make to my service:
var request = new XMLHttpRequest();
request.open("OPTIONS", url, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function () {
if (request.readyState != 4) {
return;
}
var authType = request.getResponseHeader("WWW-Authenticate");
makeRequest(...);
};
request.send();
}
So what I'm trying to achieve is make a call to my endpoint to see what's the authorisation type (basic or bearer) and then when I get the auth type I will make the actual request with the proper credentials.
If I make the request manually I get the 401 unauthorised which is normal but I also get the WWW-Authenticate: Basic ... in my headers. However if I do this javascript call it will just fail with 401:unauthorised but I don't get this failed response in my callback so the authType will be undefined.
I haven't used javascript before so the question is how can I get the response in the callback even if the request failed with unAuthorised ?
XMLHttpRequest has an onerror callback that you can use:
var request = new XMLHttpRequest();
...
request.onerror = function(){
if (this.status == 401) {
}
}
...
request.send();