![](/img/trans.png)
[英]Laravel 7 - No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]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)
那么......怎么了? 為什么我的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
請求?
如果您只是將中間件添加到現有的GET
和POST
路由,並且瀏覽器正在發出OPTIONS
請求,則永遠不會訪問中間件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.