AntDesign vue学习笔记(二)axios使用

之前在vue页面中引入axios使用,本篇在mainjs中引入,这样就不用单独在每个页面引入

1、mainjs中引入axios,设置基础url

import axios from 'axios'
axios.defaults.baseURL = 'https://localhost:8080/'
Vue.prototype.axios = axios

2、在vue页面中,注意axios前需要加this.

methods: {
    login () {
      let that = this
      console.log(this.userName)
      console.log(this.password)
      this.axios
        .get('/api/login', {
          params: {
            userName: that.userName,
            password: that.password
          }
        })
        .then(function (response) {
          console.log(response)
          if (response.data.data.result === 'success') {
            that.$router.push('second')
          } else {
            alert(response.data.data.message)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }

3、function (response)中必须使用that才能获取到$router对象,有没有办法直接获取到呢,代码如下

 methods: {
    login () {
      let that = this
      console.log(this.userName)
      console.log(this.password)
      this.axios
        .get('/api/login', {
          params: {
            userName: that.userName,
            password: that.password
          }
        })
        .then((response) => {
          console.log(response)
          if (response.data.data.result === 'success') {
            this.$router.push('second')
          } else {
            alert(response.data.data.message)
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    }
  }

ES6中的 箭头函数 "=>" 内部的this是词法作用域,由上下文确定(也就是由外层调用者vue来确定)。

4、关于api/login,api login是模拟的一个json数据

4.1在项目根目录下添加data.json,内容如下

{
    "loginresult": {
      "result": "success",
      "message": ""
    }
}

4.2修改webpack.dev.conf.js文件,添加红色部分代码,关闭服务器重新npm run dev.

4.3、点击登录按钮就可以工作了。

5、如果传递比较复杂的请求,比如header添加数据,方法如下

this.axios(
        {
          method:"post",
          url:'/api/Login', 
          data:{
            username: that.userName,
            password: that.password
          }, 
          headers: {
            'Content-Type':'application/json;charset=UTF-8'
          }
        })
        .then((response) => {
          console.log(response)
        })
        .catch(function (error) {
          console.log(error)
        })
    }

6、配置跨域的方法

找到config/index.js添加如下代码

proxyTable: {
        '/api': {
            target: 'http://xx.xx.xx.xx:8080/',
            changeOrigin: true,
            pathRewrite: {'^/api': '' }
        }
    
  }

这样所有访问api接口都会走这个重定向。

7、跨域下接口两次请求处理屏蔽方法

1、可以在后端设置Access-Control-Max-Age
2、或者请求限制只允许Post,Get.

 

转载于:https://www.cnblogs.com/zhaogaojian/p/11066420.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值