关于Axios.create 和 CORS 跨域配置问题?

发现一个奇怪的问题,我已经在服务端配置了允许跨域:

header('Content-Type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

这样就正常:

import axios from 'axios';

axios.post('https://example.com/v1/login', {
  name: 'myuser',
  password: 'mypassword',
});

这样就不行

import axios from 'axios';

export const apiBase = axios.create({
  baseURL: "https://example.com/v1/",
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
});

apiBase.post('login', {
  name: 'myuser',
  password: 'mypassword',
});

控制台报错

Access to XMLHttpRequest at 'https://example.com/v1/login' 
from origin 'http://example.com' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: The 
value of the 'Access-Control-Allow-Origin' header in the response must 
not be the wildcard '*' when the request's credentials mode is 
'include'. The credentials mode of requests initiated by the 
XMLHttpRequest is controlled by the withCredentials attribute.
阅读 14.6k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏