跨域的解决方案

当前端向后端发送请求的时候,报这个错误 CORS,就是跨域问题

跨域问题是开发中经常会遇到的,对于一个URL,只要协议、域名、端口有一个不一样的时候就称为跨域。英文浏览器具有同源策略,访问的资源等必须相同,不允许xmlHtppRequest发送跨域的请求。

plain 复制代码
当访问的资源URL与当前URL的 协议、域名、端口 三者有任何一个不一样时,称为跨域
浏览器的同源策略:要求所访问资源的协议名、域名、端口必须完全相同,不允许XMLHttpRequest发
送跨域请求
解决跨越的两种方式:
后端
方式1:使用@CrossOrigin
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 允许所有路径
                .allowedOrigins("http://localhost:3000") // 允许特定来源
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
                .allowCredentials(true); // 允许携带凭证
    }
}

方式2:定义一个配置类,实现WebMvcConfigurer接口,重写addCorsMappings方法
前端

在开发服务器中配置代理,在vue.config.js 或 vite.config.js
 '/dev-api'  请求的前缀   
  proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        '/dev-api': {
          target: 'http://localhost:8080',
          // target: 'https://api.wzs.pub/mock/13',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/dev-api/, '')
        }
      }

项目上线
在nginx中配置代理,在nginx.config中配置proxy_pass
location /api/ {
     rewrite ^/api/(.*)$ /$1 break; //将api去掉
proxy_pass http://localhost:8888; //转发的代理服务器
}
相关推荐
ai小鬼头10 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心1 小时前
vben 之 axios 封装
前端·javascript·学习
遗憾随她而去.1 小时前
uniapp 中使用路由导航守卫,进行登录鉴权
前端·uni-app
xjt_09012 小时前
浅析Web存储系统
前端
foxhuli2292 小时前
禁止ifrmare标签上的文件,实现自动下载功能,并且隐藏工具栏
前端
青皮桔3 小时前
CSS实现百分比水柱图
前端·css
影子信息3 小时前
vue 前端动态导入文件 import.meta.glob
前端·javascript·vue.js