产生跨域访问的情况主要是因为请求的发起者与请求的接受者1、域名不同;2、端口号不同
下面给出详细步骤:
- 如果要用到Cookie,那么需要在前端设置.withCredentials=true
- 在后端写一个配置类CorsConfig,这个类继承WebMvcConfigurerAdapter,在里面进行后台跨域请求配置。
注意: 要将
$http中的url的地址写完整,例如'http://localhost:8080/getExamsByPage',如果省略http://就无法跨域,因为它代表了协议类型
下面给出相应代码
js中的配置全局$http请求的代码:
var utils = angular.module('ecnuUtils', ['ngCookies', 'ngStorage']);
utils.config(['$httpProvider', config]);
function config($httpProvider) {
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.common = { 'Access-Control-Allow-Origin' : '*' }
}
CorsConfig的代码:
package edu.ecnu.yjsy.conf;
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 CorsConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}

本文介绍了解决跨域访问的方法,包括前端设置.withCredentials及后端配置CorsConfig类实现跨域请求。文中提供了具体的JavaScript和Java代码示例。
885

被折叠的 条评论
为什么被折叠?



