简体   繁体   English

用angular设置http标头

[英]Setting http headers with angular

I'm tring to add a header called "access-token" to all my http request like this: 我正在尝试向所有我的http请求中添加一个名为“ access-token”的标头,如下所示:

var app= angular.module("MainModule", ["ngRoute"]);

app.run(function($http){
    $http.defaults.headers.common['access-token'] =ACCESSTOKEN;
})

and in my service: 并为我服务:

 service.get= function (x) {
    console.log(ACCESSTOKEN)
    return $http({
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
        'access-token': ACCESSTOKEN
      },
      crossDomain: true,
      url: GETSERVICE.replace("{id}", x),
      dataType: 'json'
    }).then(function (response) {
      if (response.data) {
        return response.data;
      } else {
        return $q.reject(response.data);
      }
    }, function (response) {
      return $q.reject(response.data);
    });

  }

the problem is that i can't see the header in the network. 问题是我在网络中看不到标题。 There is only the OPTION request without my header. 只有OPTION请求,没有我的标题。

my Back end cors configuration is like: 我的后端cors配置如下:

response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, UPDATE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, access-token");

chain.doFilter(req, res);

Any ideas how to fix it? 任何想法如何解决?

TY TY

EDIT 1: Here is the OPTION request without modifiy headers 编辑1:这是没有修改头的OPTION请求

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: access-token
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:9080
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

and whit modify headers (worked): 并修改标题(有效):

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: access-token
Access-Control-Request-Method: GET
access-token: 1520963789861
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:8081
Origin: http://localhost:9080
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

whit modify headers I have the token in the request 修改标头我在请求中有令牌

CORS exists to secure APIs so that random clients do not make calls to them. 存在CORS来保护API,以便随机客户端不会对其进行调用。

JavaScript has to take permissions to be able to make calls to those APIs. JavaScript必须获得许可才能调用这些API。 Browser is supposed to do all the heavy lifting related to CORS. 浏览器应该完成与CORS相关的所有繁重工作。 But the only requirement is that the server should return the following HTTP headers for an OPTIONS request from a client: 但是唯一的要求是服务器应为来自客户端的OPTIONS请求返回以下HTTP标头:

Access-Control-Allow-Origin: <Origin fetched from the request>
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, DELETE
Access-Control-Allow-Headers: <ACCESS-CONTROL-REQUEST-HEADERS fetched from request>

If that is NOT an option, then on the client side, following code can be added to prevent all OPTIONS requests, which compromises security: 如果这不是一个选择,那么在客户端,可以添加以下代码来防止所有OPTIONS请求,这会损害安全性:

app.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $httpProvider.defaults.headers.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
  $httpProvider.defaults.headers.get = {};
}]);

See: https://en.wikipedia.org/wiki/Cross-origin_resource_sharing 请参阅: https//en.wikipedia.org/wiki/Cross-origin_resource_sharing

That OPTIONS request is called " preflight request ". 该OPTIONS请求称为“ 预检请求 ”。 It only checks if your client has a right to send a request at all (when a server has a configured CORS). 它仅检查您的客户端是否完全有权发送请求(当服务器具有配置的CORS时)。 If server responds positively then your browser automatically send a full request with all you provided headers. 如果服务器响应正确,则您的浏览器会自动发送包含您提供的所有标头的完整请求。

$httpProvider or $http module: $ httpProvider或$ http模块:

//with the provider, in the app.config():
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

$http.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

Ok I will tell you what were the problem. 好吧,我会告诉你问题出在哪里。

The genial man who write the rest api that I call in cross domain checked the value of the token also in the OPTION request going in null pointer. 写我在跨​​域中调用的其余api的和ial可亲的人也在空指针进入的OPTION请求中检查了令牌的值。

Solved adding a filter for the option request. 解决了为选项请求添加过滤器的问题。

TY for all 所有人的TY

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM