我尝试使用 HttpRequest (dart:html) 执行 POST 请求,以调用受基本身份验证保护的休息服务。
HttpRequest request = new HttpRequest(); // create a new XHR
var url = "http://localhost:8082/xyz";
request.open("POST", url, async: false); // POST the data to the server
String username = "foo";
String password = "bar";
final auth = CryptoUtils.bytesToBase64(UTF8.encode("$username:$password"));
request.setRequestHeader('authorization',"Basic $auth");
request.setRequestHeader('content-type',"application/json");
request.setRequestHeader("accept", "application/json");
String jsonData = '{"language":"dart"}'; // etc...
request.send(jsonData); //exception 401 Unauthorized
在执行 POST 调用之前,会在没有授权 header 的情况下执行 OPTIONS 调用(由 dart:html 发出)。这会导致 401 Unauthorized 响应。
Request header:
Accept:*/*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Access-Control-Request-Headers: authorization, content-type, accept
Access-Control-Request-Method: POST
Cache-Control: max-age=0
Connection: keep-alive
Host: localhost:8082
Origin: http://localhost:63342
Referer: http://localhost:63342/dart_client/test/all_test.html
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.0 (Dart) Safari/537.36响应头:
block 引用>Content-Length: 0
Date: Mon, 02 Feb 2015 23:33:58 GMT
Server: Jetty(9.2.7.v20150116)
WWW-Authenticate: basic realm="xyzrealm"
有没有办法向 OPTIONS 调用提供授权 header ?任何建议都会很棒。谢谢
最佳答案
OPTIONS
请求由浏览器自动发出,您无法修改该请求。服务器需要允许未经身份验证的 OPTIONS
预检请求。
参见http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0 用户凭据被排除。
关于DART HttpRequest 不为 CORS OPTIONS 请求提供授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303249/