[英]Error: CORS in laravel/VueJS ajax request
I am getting cross origin problem while placing an AJAX request using VueJS to my Laravel Application. 在将使用VueJS的AJAX请求放置到我的Laravel应用程序时,我遇到了跨源问题。 I Have written back end API with Laravel 5.3 我已经用Laravel 5.3编写了后端API
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. 如果您正在向页面所在的其他域执行XMLHttpRequest ,则您的浏览器将阻止它,因为出于安全原因,通常它允许来自同一来源的请求。 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 . 有关如何实现此目标的教程是使用CORS 。
When you are using postman they are not restricted by this policy. 使用邮递员时,它们不受此政策的限制。 Quoted from Cross-Origin XMLHttpRequest : 引用自跨域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. 常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但是它们受同一原始策略的限制。 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: 为了解决这个问题,您的外部API服务器必须通过设置以下标头来支持cors请求:
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
which can be done by laravel-cors as suggested in the comments. 可以按照评论中的建议由laravel-cors完成。
This is the Cors Middleware I use: 这是我使用的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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.