Javascript Axios.create和CORS

Javascript Axios.create和CORS,javascript,ajax,axios,Javascript,Ajax,Axios,我正在使用axios向端点发出包含数据的post请求: 这项工作: 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://

我正在使用axios向端点发出包含数据的post请求:

这项工作:

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.
实际上,没有向该请求添加标题
“Content-Type”

有人知道这里出了什么问题吗


编辑:修改以下注释

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.defaults.headers['Content-Type'] = 'pplication/json;charset=UTF-8';
apiBase.defaults.headers['Access-Control-Allow-Origin'] = 'http://example.com';
apiBase.defaults.headers['Host'] = 'example.com';
apiBase.defaults.headers['Referer'] = 'example.com';
apiBase.defaults.headers['Accept-Encoding'] = 'gzip, deflate, br';

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.

设置凭据或将内容类型设置为JSON将触发一个错误

对预飞请求的响应要求比非预飞请求更严格

其中之一是,正如错误消息所说,您不能使用通配符。必须明确指定原点。你没有那样做

实际上,没有向该请求添加标题“内容类型”


当然。飞行前未获得设置权限,因此从未发出请求。

无论出于何种原因,当withCredentials设置为true时,Axios不允许您在POST请求中以JSON对象的形式发送数据。在传递数据之前,您需要对数据进行字符串化。

我认为“application/json”就足够了。您是如何尝试的?谢谢@quentin:edited question,因为即使标题实际添加到request@EmilleC. — 错误消息显示“响应中的标题”,而不是请求