簡體   English   中英

Angular 2 - 請求的資源上沒有“Access-Control-Allow-Origin”標頭

[英]Angular 2 - No 'Access-Control-Allow-Origin' header is present on the requested resource

當我嘗試從我的Angular 2 App到我的API進行API調用時,我收到以下錯誤:

XMLHttpRequest cannot load http://localhost/myAPI/public/api/v1/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 422.

我一直在檢查網絡上的每一個問題和任何與CORS相關的問題,沒有解決我的問題!

我的Laravel API在端口80上運行。(localhost)

我的角度2應用程序在端口3000上運行。(localhost:3000)

  • 我一直在嘗試用Cors中間件啟用Laravel方面的cors
  • API調用正在使用chrome web security off。 這里的第一個答案解決了這個問題,但我真的想在每次測試我的應用時停止使用CMD和不安全的chrome版本。
  • 使用chrome擴展POSTMAN API調用我的API正在運行。

那么......怎么了? 為什么我的Angular 2應用程序無法從我的API獲取記錄?

好。 似乎需要為它配置apache。

我使用的XAMPP Web服務器,我不得不修改我的httpd.conf作為解釋這里來解決這個問題。

添加此行:

Header set Access-Control-Allow-Origin "http://localhost:3000"

解決了我的問題。

必須重新啟動apache。

打開chrome檢查工具,切換到Network選項卡並檢查Angular2發送的請求。

Headers - > Response Headers ,檢查是否存在Access-Control-Allow-Origin:* (我打賭不是)

如果您正在構建API,最簡單的解決方法是添加

if (Request::is("api/*")) {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, If-Modified-Since, Cache-Control, Pragma");
}

routes.php的開頭,使用中間件是一種更好的方法,但要確保它正常工作並將Access-Control-Allow-Origin到響應頭。

//Add this middleware in your express app
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('access-Control-Allow-Origin', '*');
next();
});

我一直在嘗試用Cors中間件啟用Laravel方面的cors

您是否已注冊路線以處理OPTIONS請求?

如果您只是將中間件添加到現有的GETPOST路由,並且瀏覽器正在發出OPTIONS請求,則永遠不會訪問中間件。

暫無
暫無

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

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