我正在使用 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.
实际上,此请求中没有添加 header '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 将触发 preflight request 。
预检响应的要求比非预检请求更严格。
其中之一是,正如错误消息所示,您不能使用通配符。您必须明确指定来源。你没有这样做。
And actually, no header 'Content-Type' is added to this request.
当然。预检未获得设置它的权限,因此从未发出请求。
关于javascript - axios.create 和 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61644995/