前后端通过axios通信,使前端能通过axios来调用后端接口
1. 前端安装axios
在前端Terminal中输入npm install axios或者vue add axios(根据vue版本来选择)来安装axios
2. 前端导入axios
在<script></script>标签中导入axios:import axios from 'axios';
3. 前端配置axios
配置axios来调用后端接口。注意:可根据不同应用场景将配置代码添加到不同地方。这里以页面刷新就调用接口来举例。该配置写在前端中。
mounted() {
const _this = this
axios.get('http://localhost:8181/getAllBooks').then(function (resp) {
console.log(resp)
_this.books = resp.data
})
}
4. 后端解决跨域问题
由于前端使用的是8080端口,为了不与前端端口重合,这里后端使用了8181端口,那么前端想在8080端口调用后端8181端口是无法实现的,这时候就需要在后端中解决跨域问题。跨域问题解决方法。
我们这里使用@CrossOrigin
注解方式解决跨域问题。
@RestController
@CrossOrigin
public class bookController {
@Autowired
private bookService bookService;
@RequestMapping(value = "getAllBooks",method = RequestMethod.GET)
public List getAllBooks(){
List<bookPojo> allBooks = bookService.getAllBooks();
return allBooks;
}
}
axios传值方式
- 后端
@RequestParam
传值方式(即问号传值方式):
axios.get('http://localhost:8181/getAllBooks?pageNum='+pageNum+'&pageSize='+pageNum+'').then((res) => {
_this.tableData = res.data.data
})
2.后端@PathVariable
传
axios.get('http://localhost:8181/getBook/1).then((res) => {
_this.tableData = res.data.data
})
3.后端@RequestBody
传值
axios.put('http://localhost:8181/updateBook',this.form).then((res) => {
if(res.data.code == 1000){
this.dialogFormVisible = false
alert("数据更新成功!");
this.$router.go(0)
}
})
axios四种传值方式
1.0get
axios.get('http://localhost:8181/getAllBooks?pageNum='+pageNum+'&pageSize='+pageNum+'').then((res) => {
_this.tableData = res.data.data
})
2.0 put
axios.put('http://localhost:8181/updateBook',this.form).then((res) => {
if(res.data.code == 1000){
this.dialogFormVisible = false
alert("数据更新成功!");
this.$router.go(0)
}
})
3.0 delete
axios.delete('http://localhost:8181/deleteBookById/'+this.id+'').then((res) => {
if(res.data.code == 1000){
this.$router.go(0)
}
})
4.0 post
axios.post('http://localhost:8181/addBook',this.ruleForm).then((res) => {
// console.log("添加数据返回结果为:",res)
if(res.data.code == 1000){
alert('提交成功!');
this.$router.push('/page01')
}else {
alert('提交失败,请联系管理员!');
}
})