本文承接自跨域請求問題淺解-CSDN博客
后端:
//主啟動類
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
//控制類
@RestController
@RequestMapping("/greeting")
public class FirstController {@GetMapping("/data")public Map<String, String> greeting() {return Map.of("message", "Hello World of Spring Boot!");}
}
方式一:前后端同源
前端:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><button id="fetchData">確認</button><div id="content"></div><script>document.getElementById("fetchData").addEventListener("click", function() {fetch("/greeting/data").then(response => response.json()).then(data => {document.getElementById("content").innerHTML =`<p>從后端獲得數據: ${data.message}</p>`;// if (data && data.message) {// document.getElementById("content").innerHTML =// `<p>從后端獲得數據: ${data.message}</p>`;// } else {// console.error("數據格式不正確:", data);// }})// .catch(error => {// console.error("請求出錯:", error);// })})</script>
</body>
</html>
方式二:使用LIve Server代理
前端:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><button id="fetchData">確認</button><div id="content"></div><script>document.getElementById("fetchData").addEventListener("click", function() {fetch("http://localhost:8080/greeting/data").then(response => response.json()).then(data => {document.getElementById("content").innerHTML =`<p>從后端獲得數據: ${data.message}</p>`;// if (data && data.message) {// document.getElementById("content").innerHTML =// `<p>從后端獲得數據: ${data.message}</p>`;// } else {// console.error("數據格式不正確:", data);// }})// .catch(error => {// console.error("請求出錯:", error);// })})</script>
</body>
</html>
后端配置 CORS,將其添加到主啟動類同一目錄下
@Configuration
public class CorsConfig {@Beanpublic WebMvcConfigurer corsConfigurer() {return new WebMvcConfigurer() {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://127.0.0.1:5500").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*").allowCredentials(true);}};}
}