前端三件套+springboot后端连通尝试
本文承接自跨域请求问题浅解-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);}};}
}