代码之家  ›  专栏  ›  技术社区  ›  yevg

访问API中的自定义标头

  •  1
  • yevg  · 技术社区  · 7 年前

    我正在向我使用通过AngularJS进行的AJAX调用控制的API发送一个自定义头。

    客户(AngularJS)

    var authorization_token = 'qwerty';
    var custom_token_value = 'abc123';
    
    $http.get('http://api.mywebsite.com/endpoint',{ headers:{'Auth':authorization_token,'Custom_Header':custom_token_value} }).then(function(res){ 
    
        console.log(res.data);
    
    });
    

    服务器(PHP 5.6)

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Auth, Custom_Header"); 
    
    $headers = getallheaders();
    
    print_r($headers);
    

    回答

    Array
    (
        [Accept-Language] => en-US,en;q=0.9
        [Accept-Encoding] => gzip, deflate
        [Referer] => http://localhost:8080/
        [Auth] => qwerty
        [User-Agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36
        [Origin] => http://localhost:8080
        [Accept] => application/json, text/plain, */*
        [Connection] => close
        [Host] => api.mywebsite.com
    )
    

    为什么我看不见 Custom_Header ?

    1 回复  |  直到 7 年前
        1
  •  1
  •   yevg    7 年前

    对于任何有这个问题的人,经过反复尝试,我发现 Custom_Header 没有出现是因为它包含 _ (下划线)字符。下划线字符显然从标题键中删除。

    更多信息请点击此处: Why underscores are forbidden in HTTP header names