Reputation: 2447
I want to send a request from a dummy webpage to a web app (deployed on a server in the same sub net). The thing is that I can't use jQuery.
Only JS (doesn't work):
var $token;
var username = "user1";
var password = "123456";
var url = "http://192.168.110.35:8080/wwdf/api/login";
var data = {"username": username, "password": password};
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200) {
$token = xhr.responseText.access_token;
} else {
console.log("Error: readyState = " + xhr.readyState + " | Status " + xhr.status);
}
};
xhr.send(JSON.stringify(data));
JQuery (works):
$.ajax({
method: 'POST',
url: url,
contentType: 'application/json',
username: username,
password: password,
data: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'text/plain'
},
success: function (response) {
token = response.access_token;
$("#btn").prop('disabled', true);
}
});
Error:
XMLHttpRequest cannot load http://192.168.110.35:8080/wwdf/api/login. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Network monitoring:
Response
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:accept, content-type, x-auth-token
Access-Control-Allow-Methods:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Content-Length:0
Date:Mon, 29 Feb 2016 15:59:29 GMT
Server:Apache-Coyote/1.1
Request Headers
Request
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:max-age=0
Connection:keep-alive
Host:192.168.110.35:8080
Origin:http://192.168.12.69
Referer:http://192.168.12.69/...
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36
I don't know what I'm doing wrong, please help !
Upvotes: 2
Views: 3771
Reputation: 1198
You need to configure your server to respond with authorization
in the Access-Control-Allow-Headers
header. Right now, that header is only set to accept, content-type, x-auth-token
by your server. Or you need to remove the Authorization
header from your JS example. In the JS example you set it, but in JQuery you don't. That's why you are getting different results.
Upvotes: 2