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

FlexUI
  • 120

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

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.
回复
阅读 1.1k
1 个回答
✓ 已被采纳
宣传栏