vue中:proxy代理
proxy: {
'/dev-api': { // 匹配所有以 '/dev-api'开头的请求路径
target: 'http://localhost:8800',//将浏览器中请求的路径(‘/dev-api’前的路径)改为target中的路径
changeOrigin: true, // 支持跨域
pathRewrite: { // 重写路径
'^/dev-api':'' //将‘/dev-api’路径修改为''
}
}
}
}
代码表现形式
这个代码的意思就是:
浏览器发送来一个请求:
http://localhost:9528/dev-api/system/index/login
然后在vscode中有个代理拦截请求,将请求修改后并、转发
这个请求修改为:
http://localhost:8800/system/index/login
转发,转发给服务器
小结:
这个proxy在实现一个前端框架的接口中遇到,该前端本身有自己的api接口,在后端实现该接口时,需要修改前端接口的请求路径和端口号
上面这种方式是实现前端代理跨越,当然后端也有跨域方式。
如:页面发请求为http://localhost:9090,后端请求 http://localhost:8800在后端实现跨域。
后端的跨域 ,之前使用过那个@CrossOrigin注解但还是出现问题,好像因为版本有点问题,为了简便,我通过重写addCorsMappings方法实现跨域 )
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @Classname CorsConfig
* @Description
* @Date 2023/6/8 21:37
* @Created by cc
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 拦截所有的请求
//.allowedOrigins("*")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("*") // 允许跨域的方法,可以单独配置
.allowedHeaders("*"); // 允许跨域的请求头,可以单独配置
}
}
究其原因后端跨域还是在SpringMVC中。