我正在使用 axios 向端点发出包含数据的帖子请求:这有效: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.
2 回答

慕码人2483693
TA贡献1860条经验 获得超9个赞
设置凭据或将内容类型设置为 JSON 将触发预检请求。
对预检的响应的要求比对非预检请求的要求更严格。
其中之一是,正如错误消息所说,您不能使用通配符。您必须显式指定原点。你没有那样做。
实际上,没有向此请求添加标头“内容类型”。
自然。印前检查未获得设置它的权限,因此从未发出请求。

喵喵时光机
TA贡献1846条经验 获得超7个赞
无论出于何种原因,Axios 都不允许在将 withCredentials 设置为 true 时以 JSON 对象的形式在 POST 请求中发送数据。在传递数据之前,您需要将数据字符串化。
添加回答
举报
0/150
提交
取消