Vue.js 和 Java 后端的交互
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
在Vue.js和Java后端之间进行数据交换,通常使用HTTP请求。以下是一个使用axios在Vue.js前端发送GET请求和在Java后端接收并处理请求的简单示例。
Vue.js前端 (使用axios发送GET请求):
<template>
<div>
<button @click="fetchData">Fetch Data</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'DataFetcher',
methods: {
fetchData() {
axios.get('http://localhost:8080/data/fetch')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
}
}
};
</script>
Java后端 (使用Spring Boot处理请求):
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
@GetMapping("/data/fetch")
public String fetchData() {
// 这里只是示例,通常你会从数据库或其他服务获取数据
return "Sample data";
}
}
确保你的Vue.js项目已经安装了axios依赖,并且Java后端运行在8080端口。当你在Vue.js应用中点击按钮时,它将向http://localhost:8080/data/fetch
发送GET请求,Java后端接收请求并返回数据。
评论已关闭