简体   繁体   English

CORS 块 Laravel + VueJS Axios

[英]CORS Block Laravel + VueJS Axios

I am building my own API with Laravel version 7, though when I make a request to Laravel from vuejs (actually quasar), I'm getting: "Access to XMLHttpRequest at 'http://127.0.0.1:8080/api/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ". I am building my own API with Laravel version 7, though when I make a request to Laravel from vuejs (actually quasar), I'm getting: "Access to XMLHttpRequest at 'http://127.0.0.1:8080/api/login '来自原点'http://localhost:8080' 已被 CORS 策略阻止:请求的资源上不存在'Access-Control-Allow-Origin' header。“。

Just for a dirty quick fix, I've try to add (to my top bootstrap/app.php file):只是为了一个肮脏的快速修复,我尝试添加(到我的顶级 bootstrap/app.php 文件):

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');

I have also tried to add this to a middleware class like following:我还尝试将其添加到中间件 class 中,如下所示:

return $next($request)
          ->header('Access-Control-Allow-Origin', '*')
          ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

The error still persists.错误仍然存在。 What am I missing here?我在这里想念什么?

在此处输入图像描述

You can handle CORS with set a proxy in vue config您可以通过在 vue config 中设置代理来处理 CORS

vue.config.js vue.config.js

module.exports = {
 devServer: {
  proxy: 'http://localhost:8080',
 }
}

You should send the header Access-Control-Allow-Origin in all your responses from the server.您应该在来自服务器的所有响应中发送 header Access-Control-Allow-Origin I do not know Laravel pretty well, but it seems that only options are sending this response header.我不太了解 Laravel,但似乎只有选项发送此响应 header。

You can debug this using your browser.您可以使用浏览器对此进行调试。 Open the network tab and check if your server is sending the response header Access-Control-Allow-Origin within all requests.打开网络选项卡并检查您的服务器是否在所有请求中发送响应 header Access-Control-Allow-Origin

Although this should solve the issue, you should remember that, in production, using a wildcard (*) for CORS is a bad practice and should be replaced by a whitelist when deploying your app虽然这应该可以解决问题,但您应该记住,在生产中,对 CORS 使用通配符 (*) 是一种不好的做法,在部署应用程序时应该用白名单替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM