2016-12-07 154 views
0

我在使用VueJS向我的Laravel应用程序发出一个AJAX请求时遇到了跨源问题。 我已经写了后端API与Laravel 5.3错误:laravel中的CORS/VueJS ajax请求

+0

您将需要处理的起源请求你的API中。你可以使用这样的东西:https://github.com/barryvdh/laravel-cors –

+0

你应该总是使用谷歌之前提问或至少堆栈的搜索。你会得到至少几个答案,而不会问很多很多人一样的问题 –

回答

0

这是一个Cors中间件使用:

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; 
    } 
} 
+0

谢谢!我更新了这个中间件,并与我的laravel 5.3一起使用 – webDev

2

如果你正在做一个XMLHttpRequest到不同的域比你的页面上,浏览器会阻止它,因为它通常允许出于安全原因,同一产地的请求。当你想做一个跨域请求时,你需要做一些不同的事情。有关如何实现该目标的教程是Using CORS

当您使用邮递员时,他们不受此政策的限制。从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.

为了解决这个问题,您的外部API服务器可以通过设置下列头支持CORS请求:

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

可以通过laravel-cors完成作为意见提出。