主要内容
前面我创建了前后端,前后端的端口是不一致的,前端端口为8080,后端端口为9000,这篇记录处理跨域请求。
主要步骤
在后端项目中,新加文件夹util,新加文件WebConfig
在文件中,处理跨域请求,写明访问路径,请求来源,方法,访问时间等配置。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:8080", "null")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
在前端中,在main.js文件中,加入后端端口。
import axios from 'axios'
Vue.prototype.$http = axios
axios.defaults.baseURL = 'http://localhost:9000'
到这里,前后端跨域请求就处理完成。