七牛云前端表单直传文件提示Access-Control-Allow-Origin跨域如何解决?
nbstudy 发表于 2024-07-16 08:40:16
使用过七牛云的小伙伴都知道,七牛云支持前端通过表单直传,只需要一个token
即可。
通过如果我们使用 element plus 等UI框架自带的上传组件,只需简单配置 action
、data
或 header
等属性即可,框架自动帮我们进行上传。
但是如果需要自定义一个文件上传组件,有可能会提示跨域。
例如,我们可以使用axios
进行自定义上传:
javascript
const axiosInstance = axios.create({
// 问题就在这里
withCredentials: true
timeout: 150000,
});
const uploadFile: RequstType = async (url, params) => {
const config = {
headers: { "Content-Type": "multipart/form-data" },
};
return await axiosInstance.post(url, params,config);
};
const fd = new FormData();
// 选择的文件
fd.append("file", file);
// 后端返回的上传凭证
fd.append("token", "token");
uploadFile("https://upload.qiniup.com/",fd)
错误解读
上述代码看似没有问题,但是就是会提示跨域。

我们分析以下报错的提示:
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.
错误信息的意思是:
Preflight request
:这是一个预检请求,浏览器在发送实际请求之前,会先发送一个 OPTIONS 请求,以确定是否安全可以发送请求。
Access-Control-Allow-Origin header
:这个响应头必须包含一个明确的允许访问的源,而不是通配符 *。
- The request's credentials mode is 'include':这意味着请求包含了凭据(如Cookies或HTTP认证信息),因此浏览器要求服务器明确允许来自你的源的请求。
- The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute:这表明请求是通过 XMLHttpRequest 发起的(此处为axios),并且
withCredentials
属性被设置为 true。
解决方案
很明显,我们无法对七牛云的服务端进行配置。那只能通过前端配置 withCredentials
即可.
修改代码如下:
javascript
const uploadFile: RequstType = async (url, params) => {
const config = {
headers: { "Content-Type": "multipart/form-data" },
// 不携带cookie即可
withCredentials: false
};
return await axiosInstance.post(url, params,config);
};