Vditor文件上傳跨域
官網是發了一次請求,而我這里發了兩次請求。
有一個option請求,形成了跨域。
雖然我在后端配置了允許跨域,但事實上,我用JWT的攔截器把文件上傳的接口給攔截了。
且走的是OPTION,然后報錯了跨域。
我的MVC攔截器
this.vditor = new Vditor('vditor', {
height: 360,
toolbarConfig: {
pin: true,
},
cache: {
enable: false,
},
upload: {
fieldName:"file",
headers:{
token:main.local.get("piyu").token,
},
withCredentials:true,
accept: 'image/*,.mp3, .wav, .rar',
token: main.local.get("piyu").token,
url:this.$api.API_UPLOAD_FILE,
linkToImgUrl:this.$api.API_UPLOAD_FILE,
filename (name) {
return name.replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '').
replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '').
replace('/\\s/g', '')
},
},
after: () => {
this.vditor.setValue("");
},
toolbar: [
'emoji',
'headings',
'bold',
'italic',
'strike',
'link',
'|',
'list',
'ordered-list',
'check',
'outdent',
'indent',
'|',
'quote',
'line',
'code',
'inline-code',
'insert-before',
'insert-after',
'|',
'upload',
// 'record',
'table',
'|',
'undo',
'redo',
'|',
'edit-mode',
// 'content-theme',
'code-theme',
'export',
{
name: 'more',
toolbar: [
'fullscreen',
'both',
'preview',
'info',
'help',
],
}],
})
package com.pipihao.piyu.config;
import com.pipihao.piyu.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
/**
* 解決跨域
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","OPTIONS")
.maxAge(3600);
}
/**
* 攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/**") //攔截的接口,(理論上是所有的都攔截了)
.excludePathPatterns(
"/login",
"/user/register",
"/file/upload",
"/class/all" //所有分類
); // 不攔截的鏈接前端得加上“/”
}
}
解決方案:不攔截文件上傳接口,在文件上傳的接口內使用JWT驗證即可。
@PostMapping("/file/upload")
public Map<String,Object> upload(@RequestParam("file") MultipartFile filename, HttpServletRequest request) throws IOException {
Map<String,Object> map = new HashMap<>();
try{
JWTUtils.verifyToken(request.getHeader("token"));
}catch (Exception e){
/*此處記錄來訪者的ip*/
map.put("msg","非法數據訪問");
return map;
}
//文件保存
return map;
}