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

关于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.


回答:

withCredentialstrue时,不允许设置Access-Control-Allow-Origin:*

需要指定origin

https://developer.mozilla.org...

https://ben-lau.github.io/%E8...

以上是 关于Axios.create 和 CORS 跨域配置问题? 的全部内容, 来源链接: utcz.com/p/936180.html

回到顶部