package com.wen.wdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfig implements WebMvcConfigurer { //添加到容器中管理 @Bean public CorsFilter corsFilter() { // 1.添加CORS配置信息 CorsConfiguration config = new CorsConfiguration(); // 放行哪些原始域 config.addAllowedOrigin("*"); // 是否发送Cookie信息 config.setAllowCredentials(true); // 放行哪些原始域(请求方式) config.addAllowedMethod("*"); // 放行哪些原始域(头部信息) config.addAllowedHeader("*"); // 暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息) //config.addExposedHeader("*"); config.addExposedHeader("Content-Disposition"); // 2.添加映射路径 UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); // 3.返回新的CorsFilter. return new CorsFilter(configSource); } }
fetch模拟浏览器post请求,下载
post请求
fetch(new Request('url',{
method:'POST',
headers: {'Content-Type': 'application/json','session':'{}'},
body:"{}"
})).then((resp)=>{console.log(resp)})
post下载:
fetch('url', {
method: 'POST',
body: JSON.stringify({}),
headers: {'Content-Type': 'application/json;charset=UTF-8','session':'{}'}
}).then(function(response) {
response.headers.forEach(function(val, key) { console.log(key + ' -> ' + val); });
//解码中文文件名
const filename = decodeURI(response.headers.get('content-disposition').split(';')[1].split('=')[1])
response.blob().then(blob => {
const link = document.createElement('a')
link.style.display = 'none'
// a 标签的 download 属性就是下载下来的文件名
link.download = filename
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
// 释放的 URL 对象以及移除 a 标签
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
})
})