后端设置允许跨域
前端设置允许跨域
前端只是允许跨域还不够,还得设置跨域的时候允许携带参数不然后端接收不到参数
后端
package com.wlqk.core.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;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
前端 使用vue 和 fetch
允许跨域 vue.config.js 中的配置
module.exports = {
devServer: {
proxy: {
"/api": { //自定义
target: "http://127.0.0.1:8089/api", //这里可以跟随项目实际部署服务器来
changeOrigin: true,
ws: true,
pathRewrite: {
"^/api": ""//自定义
}
}
}
}
}
允许跨域携带参数 mode: “cors”
import HttpFetchImpl from './HttpFetchImpl'
import constUrl from './ConstUrl';
class Http {
constructor(implement) {
this.implement = implement;
}
post(url, data) {
url = constUrl.getUrl()+url;
let pojo = {
method: "POST",
body: JSON.stringify(data),
mode: "cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
return this.implement.post(url,pojo);
}
get(url) {
return this.implement.get(url);
}
}
const http = new Http(HttpFetchImpl);
export default http;
fetch
class HttpFetchImpl{
constructor() {
}
get (url) {
return fetch(url)
.then(resp => {
let data;
try {
data = resp.json();
} catch (e) {
data = resp.text();
}
return data;
});
}
post(url, data) {
return fetch(url,data).then(resp => {
let data;
try {
data = resp.json();
} catch (e) {
data = resp.text();
}
return data;
});
}
}
const impl = new HttpFetchImpl;
export default impl;