解决angular+spring boot的跨域问题

    xiaoxiao2021-12-13  20

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

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

      下面给出详细步骤:

    如果要用到Cookie,那么需要在前端设置.withCredentials=true 在后端写一个配置类CorsConfig,这个类继承WebMvcConfigurerAdapter,在里面进行后台跨域请求配置。 注意: 要将$http中的url的地址写完整,例如'http://localhost:8080/getExamsByPage',如果省略http://就无法跨域,因为它代表了协议类型 下面给出相应代码 js中的配置全局$http请求的代码: [javascript]  view plain  copy   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的代码: [java]  view plain  copy   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);       }     
    转载请注明原文地址: https://ju.6miu.com/read-950366.html

    最新回复(0)