簡體   English   中英

角獲取請求CORS

[英]Angular get request CORS

這是我的服務

import { Injectable } from '@angular/core';
import { HttpModule,Http } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class MyDataServiceService {

  constructor(private http:Http) {}

  getData(){
    return this.http.get('http://stats.nba.com/stats/leaguedashplayerbiostats/?PerMode=Totals&Season=2016-17&LeagueID=00&SeasonType=Playoffs');
  }

}

為什么如果我從瀏覽器請求時可以獲取信息,而當我的角度應用程序請求請求被鎖定(因為缺少cors標頭)時,為什么? 我可以從前端修復它嗎?

CORS通常是服務器端的問題。 服務器必須授權客戶端訪問它。 但前提是您說它在瀏覽器中有效,則可能已實現了CORS。 您可以使用Postman之類的程序來發送請求,以檢查是否發生以下情況。

瀏覽器在您的請求稱為預檢請求之前發送了一個請求(或您可以通過Postman手動發送)。 這是為了確保服務器支持您將要調用的HTTP方法。 飛行前請求將包含原始標頭:

Origin: http://foo.example

並假設服務器已實現CORS ,它將在標頭中返回以下內容:

Access-Control-Allow-Origin: *

如果存在上述行,則應該沒有問題。 因此,在angular應用程序中,您應包括第一個代碼段,服務器應返回第二個代碼段。 如果您確實有權訪問后端,請確保在響應中插入了第二個代碼段。

飛行前的請求和響應交換應類似於以下內容(查看完整文章 )。 我也從這篇文章中學到了很多

飛行前要求:

OPTIONS /resource/foo 
Access-Control-Request-Method: DELETE 
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

響應:

HTTP/1.1 200 OK
Content-Length: 0
Connection: keep-alive
Access-Control-Allow-Origin: https://foo.bar.org
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400

因此,在您的應用中,您需要包括Origin : http://your.domain ,類似於以下請求和響應:

GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: http://foo.example/examples/access-control/simpleXSInvocation.html
Origin: http://foo.example


HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2.0.61 
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml

[XML Data]

CORS接頭通常是后端的一部分。 如果您更好地使用django

pip install django-cors-headers

https://github.com/ottoyiu/django-cors-headers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM