json Vue Axios CORS 政策:没有“Access-Control-Allow-Origin”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55883984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:09:26  来源:igfitidea点击:

Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

jsonvue.jsaxios

提问by Ashtav

I build an app use vue and codeigniter, but I have a problem when I try to get api, I got this error on console

我使用 vue 和 codeigniter 构建了一个应用程序,但是当我尝试获取 api 时遇到问题,我在控制台上收到此错误

Access to XMLHttpRequest at 'http://localhost:8888/project/login' 
from origin 'http://localhost:8080' has been blocked by CORS policy: 
Request header field access-control-allow-origin is not allowed 
by Access-Control-Allow-Headers in preflight response.

I have been try like this on front-end (main.js)

我一直在前端尝试这样(main.js)

axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

and this on backend (controller)

这在后端(控制器)

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

and vue login method

和vue登录方法

this.axios.post('http://localhost:8888/project/login', this.data, {
   headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
          "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
        }
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err.response);
      });

I've searched and tried in stackoverflow but does not work, how I can solve it? thank you so much for your help

我已经在 stackoverflow 中搜索并尝试过,但不起作用,我该如何解决?非常感谢你的帮助

回答by Eric Guan

CORS is the server telling the client what kind of HTTP requests the client is allowed to make. Anytime you see a Access-Control-Allow-*header, those should be sent by the server, NOT the client. The server is "allowing" the client to send certain headers. It doesn't make sense for the client to give itself permission. So remove these headers from your frontend code.

CORS 是服务器告诉客户端允许客户端发出什么样的 HTTP 请求。任何时候你看到一个Access-Control-Allow-*标题,那些应该由服务器发送,而不是客户端。服务器“允许”客户端发送某些标头。客户给自己许可是没有意义的。因此,请从前端代码中删除这些标头。

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

this.axios.post('http://localhost:8888/project/login', this.data, {
   headers: {
          // remove headers
        }
      }).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err.response);
      });

For example, imagine your backend set this cors header.

例如,假设您的后端设置了这个 cors 标头。

header("Access-Control-Allow-Methods: GET");

header("Access-Control-Allow-Methods: GET");

That means a client from a different origin is only allowed to send GET requests, so axios.getwould work, axios.postwould fail, axios.deletewould fail, etc.

这意味着来自不同来源的客户端只被允许发送 GET 请求,所以axios.get会工作,axios.post会失败,axios.delete会失败等等。

回答by Sil2

in my case curl && postman works but not vue axios.post

在我的情况下 curl && 邮递员工作但不是 vue axios.post

Access to XMLHttpRequest at 'http://%%%%:9200/lead/_search' from origin 'http://%%%%.local' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

从源“ http://%%%%.local”访问“ http://%%%%:9200/lead/_search”的XMLHttpRequest已被 CORS 策略阻止:请求标头字段 access-control-allow-预检响应中的 Access-Control-Allow-Headers 不允许原点。

So, the issue is on vue side not the server!

所以,问题出在 vue 端而不是服务器!

The server response contains "access-control-allow-origin: *" header

服务器响应包含“access-control-allow-origin: *”标头

回答by Chameera W. Ashan

This may occur you are trying call another host for ex- You Vue app is running on localhost:8080 but your backend API is running on http://localhost:8888In this situation axios request looking for this localhost:8080/project/login instead of this http://localhost:8888/project/login

可能会发生这种情况,您正在尝试为前呼叫另一个主机 - 您的 Vue 应用程序正在 localhost:8080 上运行,但您的后端 API 正在http://localhost:8888 上运行在这种情况下,axios 请求正在寻找此 localhost:8080/project/login而不是这个 http://localhost:8888/project/login

To solve this issue you need to create proxy in your vue app

要解决此问题,您需要在 vue 应用程序中创建代理

Follow this instruction Create js file vue.config.js or webpack.config.js if you haven't it yet inside root folder

按照此说明创建 js 文件 vue.config.js 或 webpack.config.js 如果您还没有在根文件夹中

then include below

然后包括在下面

module.exports = {
 devServer: {
     proxy: 'https://localhost:8888'
 } }

If you need multiple backends use below

如果您需要多个后端,请在下面使用

module.exports = {
devServer: {
    proxy: {
        '/V1': {
            target: 'http://localhost:8888',
            changeOrigin: true,
            pathRewrite: {
                '^/V1': ''
            }
        },
        '/V2': {
            target: 'https://loclhost:4437',
            changeOrigin: true,
            pathRewrite: {
                '^/V2': ''
            }
        },

    }
}

If you select the second one in front of the end point use the V1 or V2 ex - your end point is /project/login before it use V1/project/login or V2/project/login as per the host

如果您选择终点前面的第二个,请使用 V1 或 V2 ex - 您的终点是 /project/login,然后根据主机使用 V1/project/login 或 V2/project/login