簡體   English   中英

Angular2標頭

[英]Angular2 Headers

當我調用沒有頭的服務器時,它的工作和服務器返回json:

this.http.get(url)

但是當我添加標題時:

var headers = new Headers({'x-id': '1'});
this.http.get(url, {'headers': headers})

瀏覽器返回錯誤:

XMLHttpRequest cannot load http://domain/api/v1/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

我也試過添加Origin標題 - 瀏覽器錯誤: Refused to set unsafe header "Origin"

Access-Control-Allow-Origin標頭 - 沒有效果


在服務器(Laravel)上我創建了中間件Cors.php

<?php

namespace App\Http\Middleware;

use Closure;

class Cors {
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', 'http://localhost:3000')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'x-id');
    }
}

我是angular2和CORS請求的新手,不知道該怎么做。

  • Angular:2.0.0-beta.0
  • Laravel:5.0
  • 瀏覽器:谷歌瀏覽器

使用CORS的預檢請求意味着OPTIONS HTTP請求在實際請求之前執行。 您從一個簡單的請求切換到一個請求,因為您在GET方法的情況下添加自定義標頭。 此鏈接可以幫助您了解會發生什么: http//restlet.com/blog/2015/12/15/understanding-and-using-cors/

FYI在執行跨域請求時,瀏覽器會自動添加Origin標頭。

我認為您的問題在Access-Control-Allow-Origin標頭內。 您必須設置發出呼叫的主機,而不是服務器的地址。 你應該有這個(如果你的Angular2應用程序在localhost:8080上運行):

return $next($request)
        ->header('Access-Control-Allow-Origin', 'http://localhost:8080')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'x-id');

希望它對你有幫助,蒂埃里

我在Angular2應用程序中遇到了同樣的問題。 如前所述,問題是在客戶端發出每個請求之前,將預檢請求發送到服務器。

這種請求具有OPTIONS類型,服務器有責任發回狀態為200的預檢響應 ,並設置標頭以接受來自該客戶端的請求。

這是我的解決方案(快遞):

// Domain you wish to allow
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'YOUR-CUSTOM-HEADERS-HERE');

// Set to true if you need the website to include cookies in  requests
res.setHeader('Access-Control-Allow-Credentials', true);

// Check if Preflight Request
if (req.method === 'OPTIONS') {
    res.status(200);
        res.end();
}
else {
    // Pass to next layer of middleware
    next();
}

通過這種方式,客戶端將獲得授權,您將能夠在所有請求中設置自定義標頭。 在您的情況下,您必須在Access-Control-Allow-Headers選項中設置x-id

在您的情況下,服務器必須使用以下標頭響應預檢請求:

Access-Control-Allow-Origin: *

X-Custom-HeaderAccess-Control-Allow-Methods: GET,POST,PUT,DELETE

Access-Control-Allow-Headers :x-id

請注意,對於Access-Control-Allow-Origin HTTP標頭,最佳做法是設置明確托管angular2應用程序的域而不是*,這對於不控制所有使用者的公共API是必需的!

我強烈建議您閱讀以下有關CORS的文章:

http://www.html5rocks.com/en/tutorials/cors/

我一直在開發一個帶有c# web api后端的angular2應用程序,並且遇到了cors設置的問題。

真正的問題原來不是cors設置,而是發送到api的數據(js日期對象到c#datetime類型沒有正確排列)。 但是,在您的情況下,是否必須在標頭中傳遞x-id而不是作為請求的參數? 例如,你可以做這樣的事情:

getYourDataType(id: number): Observable<YourDataType> {
    return this.http.get(url + '/' + id.toString())
        .map((response: Response) => <YourDataType>response.json());

從處理這個問題后的研究來看,似乎angular會試圖找到你想要擊中的端點,找不到它,然后假設原因必須是cors設置的錯誤,而不是客戶端數據。

你說當你沒有在你的請求上設置任何標題時api返回數據,所以如果從標題更改為參數不起作用,你可以嘗試使用像fiddler或chrome的網絡選項卡這樣的工具檢查請求開發工具,看看角度是否按照您的預期應該構建每個請求。 或者通過在fiddler中手動構建請求來比較結果,可能會非常有啟發性地說明為了給出這個意外響應而發生了什么。

無論如何,確定您的數據存在問題,而不是使用cors設置是非常困難的。 Angular讓你看到一個完全錯誤的東西,試圖找出一個非常簡單的問題。 我希望這有助於某人。

問題是您還需要設置允許的標頭。 這就是為什么它不起作用。 要使其與簡單的angular2 http請求一起使用,您需要添加以下標頭:

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); // In your case also add x-id or what you are also using. 
    header('Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS');

嘗試以下代碼,這應該工作

let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('x-id','1');
this.http.get(url, {'headers': headers}).subscribe(
  response => {...},
  error => {...}
);

暫無
暫無

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

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