目录
跨域(Cross-Origin)是指在浏览器中,当前网页的协议、域名或端口与请求目标的协议、域名或端口不相同,即存在跨域请求的情况。
- 跨域通过前端解决(一般都是开发模式使用,前提是后端没有配置跨域):可以通过前端解决,后端不需要更改。
- 跨域通过后端解决(一般是测试模式或者生产模式使用):可以通过后端解决,前端不需要更改。
注意:如果后端解决了跨域,前端的本地、测试、开发模式都不需要解决跨域了
如果后端解决了跨域,前端发送的请求url和端口 就是后端服务的url和端口
1、前端解决跨域
1、在vue.config.js中添加
module.exports = {
devServer: {
proxy: {
//拦截路径携带/api
'/api': {//表示拦截以/api开头的请求路径
//替换源和后端源一直 http://localhost:8080 --> http://localhost:9090
target: 'http://localhost:9090',
changOrigin: true,//是否开启跨域
pathRewrite: {
'^/api': '' //重写api,把api变成空字符,因为我们真正请求的路径是没有api的
}
}
}
}
};
2、在本地环境变量中设置基础url + /api/
3、举例说明
this.$request.post('user/register', {
userId: this.form.userId,
userName: this.form.userName,
password: this.form.password,
})
.then((res) => {
let result = res;
if (result.code == "200") {
this.$message({
message: result.message,
type: "success",
});
window.sessionStorage.setItem("token", result.token);
window.sessionStorage.setItem("user", JSON.stringify(result.user));
this.form.userId = "";
this.form.userName = "";
this.form.password = "";
this.form.confirmPassword = "";
this.$router.push('/login')
} else if (result.code == "500") {
this.$message({
message: result.message,
type: "error",
});
}
})
.catch(() => {
this.$message.error("注册失败");
});
2、后端解决跨域
-
新增跨域配置类,即可
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 CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*");
}
};
}
}