dopq87915
dopq87915
2016-12-07 00:37

错误:laravel / VueJS ajax请求中的CORS

I am getting cross origin problem while placing an AJAX request using VueJS to my Laravel Application. I Have written back end API with Laravel 5.3

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duanjia9577 duanjia9577 5年前

    This is the Cors Middleware I use:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class CorsMiddleware
    {
        public function handle($request, Closure $next)
        {
            $headers = [
                'Access-Control-Allow-Origin'      => '*',
                'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS',
                'Access-Control-Allow-Credentials' => 'true',
                'Access-Control-Max-Age'           => '86400',
                'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
            ];
    
            if ($request->isMethod('OPTIONS')) {
                return response()->json('{"method":"OPTIONS"}', 200, $headers);
            }
    
            $response = $next($request);
            foreach($headers as $key => $value) {
                $response->header($key, $value);
            }
    
            return $response;
        }
    }
    
    点赞 评论 复制链接分享
  • dpkpaxhzffixp8426 dpkpaxhzffixp8426 5年前

    If you are doing an XMLHttpRequest to a different domain than your page is on, your browser will block it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

    When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

    Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

    To solve this, your external API server has to support cors request by setting following headers:

    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
    

    which can be done by laravel-cors as suggested in the comments.

    点赞 评论 复制链接分享

相关推荐