跨域的解决方案

当前端向后端发送请求的时候,报这个错误 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; //转发的代理服务器
}
相关推荐
liangshanbo121530 分钟前
将 Intersection Observer 与自定义 React Hook 结合使用
前端·react.js·前端框架
Python私教31 分钟前
Vue3封装通用确认删除按钮实战案例
前端·javascript·vue.js
林中白虎1 小时前
使用CSS实现酷炫加载
前端·css
资深前端之路1 小时前
vue2 将页面生成pdf下载
前端·vue.js·pdf
什么鬼昵称1 小时前
Pikachu-Cross-Site Scripting-xss之htmlspecialchars
前端·xss
猿java2 小时前
守护线程是什么?
java·前端·面试
蜡笔小新星2 小时前
在Python中,使用Pillow(PIL的更新分支)库来合并两张图片成一张上下结构的图片
前端·经验分享·python·学习·pillow
黄毛火烧雪下2 小时前
React返回上一个页面,会重新挂载吗
前端·javascript·react.js
浮华似水2 小时前
接口隔离原则在前端的应用
前端