Vue Axios CORS 政策:没有“Access-Control-Allow-Origin" [英] Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

查看:671
本文介绍了Vue Axios CORS 政策:没有“Access-Control-Allow-Origin"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

我已经在前端 (main.js) 上这样尝试过

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

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

这在后端(控制器)

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

和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);
      });

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

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

推荐答案

CORS 是服务器告诉客户端允许客户端发出什么样的 HTTP 请求.每当您看到 Access-Control-Allow-* 标头时,这些标头都应该由服务器发送,而不是客户端.服务器允许"客户端发送某些标头.客户给自己许可是没有意义的.因此,请从您的前端代码中删除这些标头.

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.

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);
      });

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

For example, imagine your backend set this cors header.

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

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

That means a client from a different origin is only allowed to send GET requests, so axios.get would work, axios.post would fail, axios.delete would fail, etc.

这篇关于Vue Axios CORS 政策:没有“Access-Control-Allow-Origin"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆