Vue axios跨域问题
什么是跨域: 跨域请求存在的原因:由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容。
需要在前后端都修改:步骤如下
在springboot后端:
config文件夹下(没有的新建就好)
添加class文件CORSConfig.java
内容如下
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
- @Description 跨域配置
- @Author hejiang
- @Date 2021/4/29 13:31
/
@Configuration
public class CORSConfig extends WebMvcConfigurerAdapter{
static final String ORIGINS[] = new String[] { “GET”, “POST”, “PUT”, “DELETE” };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
.maxAge(3600);
}
}
另一个文件:CORSFilter
内容如下:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CORSFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
然后再控制类中加上注解
@CrossOrigin
前端
import { ref } from “vue”;
import axios from “axios”;
axios.defaults.baseURL = ‘/api’;
export function postUrlAxios(url: string, data:string) {
const result = ref(null); //后端发过来的数据
const loading = ref(true); //加载中
const loaded = ref(false); //加载完成了没有
const error = ref(null); //报错
axios
.post(url, {
data,
})
.then((res) => {
loading.value = false;
loaded.value = true;
result.value = res.data;
})
.catch((e) => {
error.value = e;
console.log(请求服务器失败!${e}
);
loading.value = false;
});
return {
result,
loading,
loaded,
error,
};
}
vue.config.js
module.exports = {
devServer: {
proxy: {
“/api”: {
// 此处的写法,目的是为了 将 /api 替换成 https://www.baidu.com/
target: “http://localhost:8001/login/”,
// 允许跨域
changeOrigin: true,
ws: true,
pathRewrite: {
“^/api”: “”,
},
},
},
},
};