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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?