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注解

这个注解的作用是用来处理跨域请求的注解,让你能访问不是一个域的文件。

分析可能的错误原因:

  1. 后台的跨域配置Access-Control-Allow-Origin不能使用通配符 ‘*’;
  2. 请求的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 {
    }
}


成功
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值