访问API中的自定义标头

时间:2018-01-29 06:41:47

标签: php angularjs header http-headers cors

我正在向我使用通过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 个答案:

答案 0 :(得分:0)

对于遇到此问题的任何人,经过一些试验和错误后,我发现Custom_Header未显示的原因是因为它包含_(下划线)字符。下划线字符显然会从标题键中删除。

此处有更多信息:Why underscores are forbidden in HTTP header names

相关问题