Vue3.0向后端发起跨域请求报错
Vue3.0向后端发起跨域请求报错
1.错误信息
近期在做应届生求职网站项目,在搭建Vue3过程中向后端发起跨域请求报错,错误信息如下
Access to XMLHttpRequest at ‘http://127.0.0.1:8081/yingjiesheng/register’ from origin ‘http://127.0.0.1:8080’ has been blocked by CORS policy: 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.
2.问题分析
先看一下我的前端配置
main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import locale from 'element-plus/lib/locale/lang/zh-cn'
import 'element-plus/lib/theme-chalk/index.css'
import '@/assets/styles/base.scss'
import '@/assets/styles/overall.scss'
import '@/assets/styles/resetElement.scss'
import '@/utils/rem'
import App from './App.vue'
import router from './route/index.js'
import axios from 'axios'
const app = createApp(App) // 将默认改写为这样
axios.defaults.withCredentials = true;// 允许跨域携带cookie
axios.defaults.baseURL = 'http://127.0.0.1:8081/'; //设置默认请求地址
app.provide('$axios', axios)
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //设置默认编码方式为
app.use(router)
app.config.warnHandler = function() {
// `trace` 是组件的继承关系追踪
}
app.use(ElementPlus, { locale }).mount('#app')
axios请求 app.js
import axios from 'axios'
axios.defaults.withCredentials = true;// 允许跨域携带cookie
export function login(params){
return new Promise((resolve, reject) =>{
axios({
method: 'post',
url: '/yingjiesheng/register',
data: params
}).then(res => {
//将获取数据 同个 Promise 格式传递回 Page A
resolve(res.data);
}).catch(err => {
reject(err.data)
})
});}
后端在controller添加@CrossOrigin注解
这个注解的作用是用来处理跨域请求的注解,让你能访问不是一个域的文件。
分析可能的错误原因:
- 后台的跨域配置Access-Control-Allow-Origin不能使用通配符 ‘*’;
- 请求的origin和后台设置的origin不一致。
我的问题:后端没有编写跨域配置类
3.问题解决
编写配置类
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 单机测试时如果有跨域问题,就用这个Filter解决,把@Component前的注释移除即可
* 如果是在微服务中,跨域问题在网关层进行了解决,服务没必要再次进行处理,把@Component注释掉即可
*/
@Component
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Origin", req.getHeader("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,customercoderoute,authorization,conntectionid,Cookie");
if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
成功
分类:
vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)