一、前言
当协议名、主机名、端口名保持一致时,即不存在跨域的问题。当三者中任意一项不一样,则涉及跨域。例如:http://localhost:8080/
http:协议名
localhost:主机名
8080:端口名
二、后端解决方法
后端解决不能跨域问题。
方法一:使用注解
在需要跨域访问的controller层,添加注解:@CrossOrigin 即可完成跨域访问
方法二:新建配置类
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @ClassName: CrossConfig
* @Author: nn
* @Description: 允许跨域访问
* @Date: 2022/3/23 9:25
*/
@Configuration
public class CrossConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
// 允许跨域的域名
.allowedOriginPatterns("*") // 允许所有域
.allowedMethods("*") // 允许任何方法(post、get等)
.allowedHeaders("*") // 允许任何请求头
.allowCredentials(true) // 允许证书、cookie
.exposedHeaders(HttpHeaders.SET_COOKIE)
.maxAge(3600L); // maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
}
三、前端解决办法
前端的解决思路是配置一个代理服务器。如下图
将前后端的直接访问改为前端访问代理服务器,代理服务器再去访问后端。其中代理服务器与前端在同一服务器上。
1、如果不配置代理服务器的效果
下图为一个axios请求,端口8021为后端端口,这样启动后,会报错
2、方法一
配置:vue.config.js中配置代理服务器,proxy为实际服务器ip
使用:ip地址端口写vue项目的端口
效果:
3、方法二
配置:
使用:
效果:
4、后端代码
@Controller @RequestMapping("/test") public class TestController { @RequestMapping("/register") @ResponseBody public String getText(){ return "获取到我了"; } }
四、总结
上述即为解决axios跨域问题的方式汇总,亲测有效。欢迎留言评论