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

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

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

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

javascript 复制代码
devServer:{
    proxy:{
      "/api":{
        target:"http://localhost:9998",
        changeOrigin: true,
        pathRewrite:{"^/api": ""},
      }
    }
  }

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

javascript 复制代码
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,具体如下:

java 复制代码
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的跨域问题

相关推荐
今天也是爱大大的一天吖1 天前
vue2中的.native修饰符和$listeners组件属性
前端·javascript·vue.js
星释1 天前
Rust 练习册 16:Trait 作为返回类型
java·网络·rust
2301_796512521 天前
Rust编程学习 - 如何理解Rust 语言提供了所有权、默认move 语义、借用、生命周期、内部可变性
java·学习·rust
乐悠小码1 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
一个人的幽默1 天前
聊一下java获取客户的ip
java
披着羊皮不是狼1 天前
Spring Boot——从零开始写一个接口:项目构建 + 分层实战
java·spring boot·后端·分层
Deamon Tree1 天前
【设计题】如何实现限流器
java
STUPID MAN1 天前
Linux使用tomcat发布vue打包的dist或html
linux·vue.js·tomcat·html
短视频矩阵源码定制1 天前
矩阵系统哪个好?2025年全方位选型指南与品牌深度解析
java·人工智能·矩阵·架构·aigc
kpli901 天前
Java开发性能优化
java·jvm