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)try 这样做

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

and vue login method

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

推荐答案

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

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头.

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

这意味着来自不同来源的客户端只允许发送GET请求,因此axios.get可以工作,axios.post可以失败,axios.delete可以失败,依此类推.

Json相关问答推荐

JoltChange:将输入数组的每个对象拆分为2个独立的对象,并将其放入输出数组中

jq不会为空输入返回非零

按照对象键的值对PostgreSQL JSONB对象进行排序'

如何使用表键名称GROUP_BY

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

将PostgreSQL转换为JSON对象

JOLT转换以根据条件删除json对象

如何对未知/变量键的字典进行编码?

将不带正文的 CURL POST 转换为 RESTRequest Delphi 代码 / 为 Dropbox API /get_current_account 端点编写 Delphi 代码

Jolt 转换数组对象并将某些字段移动到嵌套数组

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

如何将该 JSON 解析为 Kotlin 类?

我无法将来自 API 的数据显示到 FlatList 中,但我在 console.log 中看到了它.问题是什么?

从 json 数组中仅提取一个值导致 vb6

使用 JQ 从文件中删除重复的 JSON 块

使用 Retrofit 解析动态密钥 Json 字符串

如何判断 JSON 响应元素是否为数组?

Jackson JSON序列化,通过级别定义避免递归

如何向 json IAM 策略添加 comments ?

FastAPI:如何将正文读取为任何有效的 json?