解決angular+spring boot的跨域問題

大浪中航行發表於2016-07-22

  產生跨域訪問的情況主要是因為請求的發起者與請求的接受者1、域名不同;2、埠號不同

  下面給出詳細步驟:


  1. 如果要用到Cookie,那麼需要在前端設定.withCredentials=true
  2. 在後端寫一個配置類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);
    }

}

相關文章