dongmi6102 2018-01-29 06:41
浏览 64
已采纳

访问API中的自定义标头

I am sending a custom header to an API that I control using an AJAX call made via AngularJS.

Client (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);

});

Server (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);

Response

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
)

Why am I not able to see Custom_Header?

  • 写回答

1条回答 默认 最新

  • douchen2025 2018-01-29 17:34
    关注

    For anyone having this issue, after some trial and error I've discovered that the reason Custom_Header was not showing up is because it contained an _ (underscore) character. Underscore characters apparently get dropped from header keys.

    More info here: Why underscores are forbidden in HTTP header names

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding