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

穿精又带淫゛_ 提交于 2020-01-09 11:08:43

问题


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/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.

I've been checking every single question on the web and anything releated to CORS, nothing solved my problem!

My Laravel API running on port 80. (localhost)

My angular 2 app running on port 3000. (localhost:3000)

  • I've been trying to enable cors in Laravel side with Cors middleware
  • The API calls are working using chrome web security off. The first answer here solves the problem, But I really want to stop using the CMD and unsecured chrome version everytime im testing my app.
  • Using chrome extension POSTMAN API calls to my API are working.

So.. What's wrong? Why my Angular 2 app cant get records from my API?


回答1:


Ok. seem like need to configure apache for it.

i'm using xampp webserver, and I had to edit my httpd.conf as explained here to solve this.

Added this line:

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

solved my problem.

Restarting apache is neccessary.




回答2:


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.




回答3:


//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();
});



回答4:


I've been trying to enable cors in Laravel side with Cors middleware

Have you registered routes to handle OPTIONS requests?

If you simply add middleware to existing GET and POST routes, and the browser is making an OPTIONS request, the middleware is never reached.



来源:https://stackoverflow.com/questions/36825429/angular-2-no-access-control-allow-origin-header-is-present-on-the-requested

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!