【发布时间】:2015-09-29 15:37:29
【问题描述】:
我正在尝试将 POST 请求发送到自定义 api(我有凭据),但不断收到 401 错误“未授权”。这是发出请求的代码的一部分:
var httpRequest = new XMLHttpRequest();
var test = [{
"action": "start",
"time": "2014-05-02T13:09:22+02:00",
"channel": {
"id": "rtvslo1"
},
"content": {
"id": "rtvslo1",
"title": "testContent",
"channel_id": "rtvslo1",
"time": "2014-05-02T13:09:22+02:00",
"duration": 3
},
"subscriber": {
"id": "f8721ca0-d1e9-11e3-9c1a-0800200c9a66",
"country": "si"
},
"device": {
"id": "012fa920-d1ea-11e3-9c1a-0800200c9a66",
"type": "tv"
},
"hd": false,
"test": true
}];
var jsonString = JSON.stringify(test);
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
httpRequest.setRequestHeader("Content-type", "application/json");
httpRequest.send(jsonString);
当我试图在 chrome 开发工具中查看错误时,我得到 OPTIONS 请求是 401 Unathorized,所以它甚至没有到达 POST。
在 chrom 开发工具中,我得到输出:名称:事件方法:OPTIONS 状态 401...
选项http://xstreampipy.tvbeat.com/api/2.0/events401(未经授权)myFunction@test.html:39onclick@test.html:60 test.html:1 XMLHttpRequest 无法加载 http://xstreampipy.tvbeat.com/api/2.0/events。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。响应的 HTTP 状态代码为 401。
任何帮助将不胜感激:)!
【问题讨论】:
-
API 是否允许发送“OPTIONS”?此外,
OPTIONS飞行前请求仅在content-type为application/json时才有意义。如果内容类型是application/x-www-form-urlencoded,您的 AP 会接受请求吗? -
API 预定义为接受 json 格式,我不知道是否允许发送 OPTIONS,API 不是我配置的,所以我不能准确告诉你(或者我可以在开发工具中阅读它标题?)。
-
您应该与您的 API 开发人员协调。如果 API 不接受 POST 请求,因为 pre-flight OPTIONS 请求被服务器拒绝,那么可能需要进行服务器端工作来适应这种情况。
标签: javascript rest http-headers cors