在SpringBoot項(xiàng)目中,如何配置跨域訪問(wèn)? springboot的跨域問(wèn)題
Voghion時(shí)尚前沿跨境問(wèn)答2025-06-127530
在SpringBoot項(xiàng)目中,我們通常使用Spring Security框架來(lái)處理跨域訪問(wèn)。以下是一個(gè)簡(jiǎn)單的示例:
- 我們需要在pom.xml中添加Spring Security依賴(lài):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
- 然后,我們需要在application.properties或application.yml文件中配置Spring Security的相關(guān)信息:
# application.properties spring.security.http.cors.enabled=true spring.security.http.cors.allowed-origins=* spring.security.http.cors.allowed-methods=GET, POST, PUT, DELETE spring.security.http.cors.allowed-headers=Content-Type, Authorization spring.security.http.cors.expose-headers=Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers
在這個(gè)例子中,我們啟用了CORS(跨域資源共享),并允許所有來(lái)源、所有方法和所有頭部進(jìn)行跨域請(qǐng)求。同時(shí),我們還暴露了Access-Control-Allow-Origin、Access-Control-Allow-Methods和Access-Control-Allow-Headers這三個(gè)HTTP頭,以便前端可以知道哪些源、方法或頭部是允許的。
- 最后,我們需要在Controller層設(shè)置@CrossOrigin注解,以指示該Controller支持跨域請(qǐng)求:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class MyController {
@GetMapping("/my-endpoint")
@CrossOrigin(origins = "*", allowedMethods = "*")
public String myEndpoint() {
return "Hello, World!";
}
}
在這個(gè)例子中,我們定義了一個(gè)名為MyController的控制器,其中包含一個(gè)名為myEndpoint的GET方法。這個(gè)方法使用了@CrossOrigin注解,表示它支持跨域請(qǐng)求。同時(shí),我們還指定了允許的所有來(lái)源("*")和所有方法("*")。
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。