vue3delete请求报403forbidden,前后端解决方式

作者 : admin 本文共1223个字,预计阅读时间需要4分钟 发布时间: 2024-06-16 共1人阅读

在做开发时,前期已经在Controller类加上@CrossOrigin(origins = "*"),发送get和post请求都没问题,但遇到delete请求时,又报出跨域问题

一.前端添加proxy代理服务器(未能解决)

在vue.config.js中使用devServer配置代理,在文件中添加

devServer:{
    proxy:{
      "/api":{
        target:"http://localhost:9998",
        changeOrigin: true,
        pathRewrite:{"^/api": ""},
      }
    }
  }

然后在你的axios配置文件中将baseURL改成

const API = axios.create({
	baseURL:'/api', 
	timeout: 2000                  
})

这是因为proxy中设置了target,则此时请求地址变为http://localhost:9998/api
但同时在proxy中添加了pathRewrite属性,它是一个正则表达式,匹配/api并替换为“”(空字符串),所以实际请求地址依然为http://localhost:9998/接口名称
使用proxy代理服务器的目的是:
解决跨域问题,我们的前端项目和代理服务器有相同的端口,访问代理服务器不存在跨域问题,然后由代理服务器去访问target目标地址。

二.后端重写addCorsMappings跨域方法(成功)

我这里是在src文件夹下,新建了config文件夹,创建了MyConfiguration类实现了WebMvcConfigurer,具体如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SuppressWarnings("deprecation")
@Configuration
public class MyConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET","POST","DELETE","PUT","OPTIONS") //允许的请求类型
                //允许携带头信息(该处为所有头信息,可根据自己的需求修改)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .maxAge(3600);
    }
}

在后端重写addCorsMappings方法成功解决了delete的跨域问题

本站无任何商业行为
个人在线分享 » vue3delete请求报403forbidden,前后端解决方式
E-->