Response to preflight request doesn't pass access control check Laravel and Ajax call

前端 未结 1 1526
予麋鹿
予麋鹿 2021-01-02 10:43

I have a REST api made in Laravel 5.1 hosted in a remote server. Now, I\', trying to consume that API from another website (that I have in local).

In Laravel I set t

相关标签:
1条回答
  • 2021-01-02 11:32

    Your backend code must include some explicit handling for OPTIONS requests that sends a 200 response with just the configured headers; for example:

    if ($request->getMethod() == "OPTIONS") {
        return Response::make('OK', 200, $headers);
    }
    

    The server-side code also must send an Access-Control-Allow-Headers response header that includes the name of the token request header your frontend code is sending:

    -> header('Access-Control-Allow-Headers', 'token')
    

    but then why with Postman work fine?

    Because Postman isn’t a web app and isn’t bound by the same-origin policy restrictions browsers place on web apps to restrict them from making cross-origin requests. Postman is a browser bolt-on for convenience of testing requests in the same way they could be made outside the browser using curl or whatever from the command line. Postman can freely make cross-origin requests.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS in contrast explains how browsers block web apps from making cross-origin requests but also how you can un-block browsers from doing that by configuring your backend to send the right CORS headers.

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains why the browser is sending that OPTIONS request your backend needs to handle.

    0 讨论(0)
提交回复
热议问题