解决angular+spring boot的跨域问题

http://blog.csdn.net/dalangzhonghangxing/article/details/51994812

产生跨域访问的情况主要是因为请求的发起者与请求的接受者1、域名不同;2、端口号不同

  下面给出详细步骤:


  1. 如果要用到Cookie,那么需要在前端设置.withCredentials=true
  2. 在后端写一个配置类CorsConfig,这个类继承WebMvcConfigurerAdapter,在里面进行后台跨域请求配置。
注意: 要将$http中的url的地址写完整,例如'http://localhost:8080/getExamsByPage',如果省略http://就无法跨域,因为它代表了协议类型

下面给出相应代码

js中的配置全局$http请求的代码:
[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. var utils = angular.module('ecnuUtils', ['ngCookies''ngStorage']);  
  2. utils.config(['$httpProvider', config]);  
  3.   
  4. function config($httpProvider) {  
  5.     $httpProvider.defaults.withCredentials = true;  
  6.     $httpProvider.defaults.headers.common = { 'Access-Control-Allow-Origin' : '*' }  
  7. }  



CorsConfig的代码:
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package edu.ecnu.yjsy.conf;  
  2.   
  3. import org.springframework.context.annotation.Configuration;  
  4. import org.springframework.web.servlet.config.annotation.CorsRegistry;  
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  6.   
  7. @Configuration  
  8. public class CorsConfig extends WebMvcConfigurerAdapter {  
  9.   
  10.     @Override  
  11.     public void addCorsMappings(CorsRegistry registry) {  
  12.         registry.addMapping("/**")  
  13.                 .allowedOrigins("*")  
  14.                 .allowCredentials(true)  
  15.                 .allowedMethods("GET""POST""DELETE""PUT")  
  16.                 .maxAge(3600);  
  17.     }  
  18.   

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值