【前端+后端】前后端分离之——前后端axios通信

前后端通过axios通信,使前端能通过axios来调用后端接口

1. 前端安装axios
在前端Terminal中输入npm install axios或者vue add axios(根据vue版本来选择)来安装axios

2. 前端导入axios
<script></script>标签中导入axiosimport 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
    })
  }

说明:
const _this = this:this为data中的数据,如果在resp方法中使用this,则指的是resp。
http://localhost:8181/getAllBooks:这是后端接口地址。
resp:后端接口返回的数据。

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;
    }
}

说明:
@CrossOrigin注解标注在类上,说明这个类中的所有接口都可以支持跨域调用。

axios传值方式

  1. 后端@RequestParam传值方式(即问号传值方式):
axios.get('http://localhost:8181/getAllBooks?pageNum='+pageNum+'&pageSize='+pageNum+'').then((res) => {
        _this.tableData = res.data.data
      })

说明:在url中可以用'+value+'方式动态传值。

  1. 后端@PathVariable传值:
axios.get('http://localhost:8181/getBook/1).then((res) => {
       _this.tableData = res.data.data
     })

说明:1就是传进去的值。

  1. 后端@RequestBody传值:
axios.put('http://localhost:8181/updateBook',this.form).then((res) => {
        if(res.data.code == 1000){
          this.dialogFormVisible = false
          alert("数据更新成功!");
          this.$router.go(0)
        }
      })

说明:this.form就是请求参数

axios四种传值方式

  1. GET
axios.get('http://localhost:8181/getAllBooks?pageNum='+pageNum+'&pageSize='+pageNum+'').then((res) => {
        _this.tableData = res.data.data
      })
  1. PUT
axios.put('http://localhost:8181/updateBook',this.form).then((res) => {
        if(res.data.code == 1000){
          this.dialogFormVisible = false
          alert("数据更新成功!");
          this.$router.go(0)
        }
      })
  1. DELETE
axios.delete('http://localhost:8181/deleteBookById/'+this.id+'').then((res) => {
        if(res.data.code == 1000){
          this.$router.go(0)
        }
      })
  1. 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('提交失败,请联系管理员!');
            }
          })
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值