Vue Axios CORS政策:否'Access-Control-Allow-Origin' [英] Vue Axios CORS policy: No 'Access-Control-Allow-Origin'

查看:131
本文介绍了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'] = '*';

,然后在后端(控制器)上

and this on backend (controller)

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天全站免登陆