关于axios的一点感悟

1、首先在vue项目中的main.js中导入axios

import axios from 'axios'

2、其次在main.js声明

Vue.prototype.axios = axios
axios.defaults.baseURL = '/api'

3、然后在main.js中将axios加入

new Vue({
  router,
   axios,//将axios配置到Vue中 ③
  render: h => h(App),
}).$mount('#app')

4、可以在相应方法上使用(如提交按钮)

 sumbit(){
          axios.post('/user/addUser',{//使用axios发送post请求,后端Api的地址,传给后端的数据
                name: this.name,
                gender: this.gender,
                avatar: this.avatar,
                account: this.account,
                password: this.password,
                email: this.email,
                phone: this.phone
          }).then(res=>{//接收后端返回的结果,包装为res
            Message.success('注册成功')
          })
        }

5、(重点)配置axios跨域问题,在vue.config.js中的加入

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave:false,  //关闭es6的语法检查
  devServer: {
    host: '127.0.0.1',
    port: '8081',
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:8888',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
})

就可以使用axios进行vue和后端的交互啦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值