【问题标题】:Accessing a custom header in the API访问 API 中的自定义标头
【发布时间】:2018-07-07 19:41:08
【问题描述】:

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

【问题讨论】:

  • 试过了吗? apache_request_headers()

标签: php angularjs header http-headers cors


【解决方案1】:

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

更多信息在这里:Why underscores are forbidden in HTTP header names

【讨论】:

    猜你喜欢
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2018-02-17
    • 2015-07-16
    • 1970-01-01
    • 2016-08-27
    相关资源
    最近更新 更多