【前后端】跨域问题

【前后端】跨域问题

Turbo 225 2023-01-25

前后端分离项目跨域问题

前言

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域。

当前页面url 被请求页面url 是否跨域 原因
http://www.demo.com http://www.demo.com/index.html 同源(协议、域名、端口号相同)
http://www.demo.com https://www.demo.com 协议不同(当前页为http,请求页为https)
http://www.demo.com http://www.study.com 主域名不同(demo/study)
http://www.demo.com http://test.demo.com 子域名不同(www/test)
http://www.demo.com:8080 http://www.demo.com:8081 端口号不同

跨域问题是出于浏览器的同源策略限制,同源策略是一种约定,它是浏览器最核心也是最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说web是构建在同源策略基础上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源就是两个页面具有相同的协议。

一、错误信息

Access to XMLHttpRequest at 'http://localhost:8080/rest/login/toLogin' from origin 'http://localhost:9000/#/login' has been blocked by CORS policy: Response to preflight request doesn't pass access control check : No 'Access-Control-Allow-Origin' header is present on the requested resouce.

二、前端解决跨域

vue项目

  1. 在config/index.js中配置proxyTable
const path = require('path')
module.exports = {
	dev: {
    	assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
        	'/api': {
            	target: 'http://localhost:8080',         // 请求后台的真实路径
                changerOrgin: true,
                pathRewrite: {
                	'^/api': ''			// 重写路径
                }
            },
        },
        host: 'localhost',
    }

}
  1. 在config/dev.env.js文件中加上一句
module.exports = merge(prodEnv, {
	NODE_ENV: '"development"',
    API: '"/api"'														// 加上这一句
})

三、后端解决跨域

springboot项目

/**
 * 后端配置解决跨域
 **/
@Configuration
public class WebMvcConfig imports WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(GlobalConstant.REST_URL_PREFIX + "/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "DELETE", "PATCH")
                .allowCredentials(true)
                .maxAge(3600);
    }
}