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

后端 未结 4 557
醉话见心
醉话见心 2020-12-11 03:55

When trying to make API Calls from my Angular 2 App to my API, I get the following error:

XMLHttpRequest cannot load http://localhost/myAPI/public/api/v1/aut         


        
4条回答
  •  旧巷少年郎
    2020-12-11 04:32

    Open chrome inspect tool, switch to Network tab and inspect the request Angular2 sent.

    In Headers->Response Headers, check whether there is Access-Control-Allow-Origin:* (I bet not)

    If you are building an API, the easiest workaround is to add

    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");
    }
    

    in the beginning of routes.php, using a Middleware would be a better approach, but make sure it is working properly and adding the Access-Control-Allow-Origin to the response header.

提交回复
热议问题