【发布时间】:2014-04-10 06:54:06
【问题描述】:
我正在尝试使用以下代码为我的所有 REST 调用设置 HTTP 标头:
app.factory('authInterceptor', function ($rootScope, $q, $window) {
return {
request: function (config) {
config.headers = config.headers || {};
config.headers.Authorization = '12345678';
return config;
},
response: function (response) {
if (response.status === 401) {
// handle the case where the user is not authenticated
}
return response || $q.when(response);
}
};
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});
我目前没有在服务器上启用任何授权。 当我省略“config.headers.Authorization = '12345678';”行时,然后 REST 调用运行良好,我得到了我的结果。在 JS 控制台中,我看到了
GET http://localhost:8080/rest/club/1 [HTTP/1.1 200 OK 7ms]
但是当我将这一行放入设置 Header 字段时,我会在 javascript 控制台中看到以下请求
OPTIONS http://localhost:8080/rest/club/1 [HTTP/1.1 200 OK 2ms]
为什么设置 Authorization Header 会将我的方法从“GET”更改为“OPTIONS”?以及如何设置自定义 Header 并且我的请求仍然有效?
改成
config.headers["X-Testing"] = '12345678';
有同样的结果。
编辑:
我尝试了答案,我正在服务器中设置以下 HTTP 标头:
response.getHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost");
response.getHeaders().putSingle("Access-Control-Allow-Header", "X-Testing");
response.getHeaders().putSingle("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
response.getHeaders().putSingle("Access-Control-Max-Age", 1728000);
我的 REST 服务器在端口 8080 上运行,用于 html/JS 的网络服务器在端口 8000 上(最初使用 file://... 但由于 Origin 为空而移动到单独的网络服务器)
response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
或
response.getHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
也没有用。
我必须在 OPTIONS 响应中返回任何内容吗?我用与 GET 相同的内容尝试了 200 OK,但我也尝试了 204 No Content。
第二次编辑:
这是 Firefox 为 OPTIONS 方法发送和接收的内容:
【问题讨论】: