1. 程式人生 > >Spring Boot Web應用開發 CORS 跨域請求設定 Invalid CORS request

Spring Boot Web應用開發 CORS 跨域請求設定 Invalid CORS request

使用SpringBoot Web開發程式時,前後端分離時,經常遇到跨域問題,特別是很多情況下Firefox瀏覽器沒有問題,而chrome瀏覽器有問題,僅僅從瀏覽器的web控制檯很難發現有效的錯誤或者告警資訊,因此在開發程式很有必要在開發階段就考慮到並配置好跨域。

SpringBoot提供的跨域配置有兩種,一種是全域性的,一種是具體到方法的。如果同時配置了那麼具體方法的優先。
具體程式碼在這裡歡迎fork,加星。

全域性跨域配置
直接上程式碼,也就提供一個自定義的WebMvcConfigurer bean,該bean的addCorsMappings方法中定義自己的跨域配置。
可以看到我的跨域配置是允許來自http://localhost:6677訪問/user/users/*的方法。等程式執行後我們可以發現如果我們的前端使用http://127.0.0.1:6677 或者我們的前端執行在http://localhost:8080都無法通過rest訪問對應的API(備註,示例程式提供了/user/users和/user/users/{userId}方法)

package com.yq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class CorsDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(CorsDemoApplication.class, args);
	}

	@Bean
	public WebMvcConfigurer corsConfigurer() {
		return new WebMvcConfigurerAdapter() {
			@Override
			public void addCorsMappings(CorsRegistry registry) {
				registry.addMapping("/user/users/*").allowedOrigins("http://localhost:6677");
			}
		};
	}
}

具體方法的跨域配置@CrossOrigin
我們可以使用@CrossOrigin在具體的API上配置跨域設定。@CrossOrigin(origins = “http://localhost:9000”)表明該方法允許來自http://localhost:9000訪問,也就是前端可以是localhost:9000。

    @ApiOperation(value = "查詢所有使用者")
    @CrossOrigin(origins = "http://localhost:9000")
    @GetMapping(value = "/users", produces = "application/json;charset=UTF-8")
    public Iterable<User> findAllUsers() {
        Collection<User> users = userMap.values();
        return users;
    }

前端程式碼
前端一個簡單的js和html,詳細內容看程式碼

$(document).ready(function() {
    $.ajax({
        url: "http://localhost:6606/user/users/2"
    }).then(function(data, status, jqxhr) {
       console.log(data);
       $('.user-id').append(data.id);
       $('.user-name').append(data.name);
       console.log(jqxhr);
    });
});

效果截圖。
示例程式前後端在一起。都執行本機的6606埠上,當你使用http://127.0.0.1:6606/時,因為跨域設定不對,前端無法訪問http://localhost:6606/user/users/2。 當前段執行在http://localhost:6677/時,前端可以正常訪問http://localhost:6606/user/users/2
在這裡插入圖片描述