Angular2 bit.ly' Access-Control-Allow-Origin'标题问题

时间:2017-01-25 10:31:59

标签: angular cors bit.ly

我正在尝试使用bit.ly API工作,但我遇到了CORS问题。我检查了所有可能的来源,但问题仍然存在。

Angular2代码:

getBitLyUrl (fullUrl : string): Observable<string> {


   let headers = new Headers({'Access-Control-Allow-Origin' : '*', 'Accept' : 'application/json' }); 
   let options = new RequestOptions({ headers: headers }); 


   let res =  this._http.get('https://api-ssl.bitly.com/v3/shorten?access_token=a4d0c60f2cfdba6941b9012c76d95a06f8b3765e&longUrl=' 
                  + fullUrl + '&format=json', options)
        .map((response: Response) => response.json());

    return res;
}

来自Chrome网络的标题:

General:
Request URL:https://api-ssl.bitly.com/v3/shorten?      access_token=a4d0c60f2cfdba6941b9012c76d95a06f8b3765e&longUrl=http://www.cyberma  .net&format=json
 Request Method:OPTIONS
 Status Code:200 OK
 Remote Address:67.199.248.20:443


Response:
Allow:GET, POST, OPTIONS
Connection:keep-alive
Content-Length:0
Content-Type:text/plain; charset=utf-8
Date:Wed, 25 Jan 2017 10:22:31 GMT
Server:nginx

Request:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en,cs;q=0.8,sk;q=0.6,de;q=0.4
Access-Control-Request-Headers:access-control-allow-origin, x-xsrf-token
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:api-ssl.bitly.com
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,   like Gecko) Chrome/55.0.2883.87 Safari/537.36

我收到此错误:

  

XMLHttpRequest无法加载   https://api-ssl.bitly.com/v3/shorten?access_token=a4d0c60f2cfdba6941b9012c76d95a06f8b3765e&longUrl=http://www.cyberma.net&format=json。   对预检请求的响应没有通过访问控制检查:否   &#39;访问控制允许来源&#39;标题出现在请求的上   资源。起源&#39; http://localhost:3000&#39;因此是不允许的   访问。

任何帮助都将受到高度赞赏!

2 个答案:

答案 0 :(得分:0)

let headers = new Headers({'Access-Control-Allow-Origin' : '*', 'Accept' : 'application/json' });。这是一个响应头。 CORS设置为安全保护后端服务器,因此后端服务器必须设置这些标头作为响应。如果您不控制服务器,除非他们批准您的域,否则无法从跨源访问它。

OPTIONS请求由浏览器设置,而不是有角度的。阅读更多abbout it here

  

跨域资源共享标准的工作原理是添加新的HTTP标头,允许服务器描述该组的起源   允许使用Web浏览器读取该信息。   此外,对于可能导致副作用的HTTP请求方法   用户数据(特别是;对于GET以外的HTTP方法或POST   用于某些MIME类型)。规范强制要求   浏览器“预检”请求,从中请求支持的方法   具有HTTP OPTIONS请求标头的服务器,然后是   来自服务器的“批准”,用实际发送实际请求   HTTP请求方法。服务器也可以通知客户端   “凭证”(包括Cookie和HTTP身份验证数据)应该   与请求一起发送。

答案 1 :(得分:0)

只需从get函数

中删除headers和options参数即可
相关问题