Axios-深入浅出

Axios请求函数会截断其身后的代码,使之不再执行!!!!

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.options(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

安装

axios、vue-axios

cnpm install --save axios vue-axios

注册

main.js
// 全局注册 axios
import Vue from ‘vue’;
import axios from ‘axios’;
import VueAxios from ‘vue-axios’;
// 默认false:axios每次请求都会生成新的session,因此关闭它!
axios.defaults.withCredentials=true;

Vue.use(VueAxios, axios);

GET

// Vue.axios.get、this.axios.get、this.$http.get
this.$http.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

POST

注意:Axios post会将传递的对象参数转为Json格式,于是服务端就不能通过setter获取参数!!!!

  • post -> @RequestBody 修饰形参可以取Json字符串
  • post Qs.stringify(data) -> 后端可正常取值(Qs库内置与axios,可直接使用)
// Vue.axios.get、this.axios.get、this.$http.get
this.$http.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
let validateCaptcha = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入验证码"));
  } else {
    // axios之后的代码不会得到执行,因此要把它们放在回调函数中
    this.axios.post(this.ruleForm.url + '/' + value).then(response => {
      if (response.data === 1) {
        callback();
      } else {
        callback(new Error("验证码错误!"));
      }
    });
  }
};
@ResponseBody
@PostMapping("/captcha/{code}")
public String captchaCode(@PathVariable String code, HttpSession session)

Axios

// Vue.axios、this.axios、this.$http
this.axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// Vue.axios、this.axios、this.$http
this.axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
let flag = "0";
this.$http.post(this.ruleForm.url,{code: value}).then(response => {
  flag = response.data;
});

文件上传

<form>
    <input type="text" value="" v-model="name" placeholder="请输入用户名">
    <input type="text" value="" v-model="age" placeholder="请输入年龄">
    <input type="file" @change="getFile($event)">
    <button @click="submitForm($event)">提交</button>
</form>
<script>
  export default {
    name: "Demo",
    data: function () {
      return {
        name: '',
        age: '',
        file: ''
      }
    },
    methods: {
      getFile(event) {
        this.file = event.target.files[0];
        console.log(this.file);
      },
      submitForm(event) {
        event.preventDefault();
        let formData = new FormData();
        formData.append('name', this.name);
        formData.append('age', this.age);
        formData.append('file', this.file);
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };
        this.$http.post('http://127.0.0.1:8081/upload', formData, config).then(function (response) {
          if (response.status === 200) {
            console.log(response.data);
          }
        })
      }
    }
  }
</script>

Token细节

浏览器会在ajax发送请求之前发送一个预请求,确认当请的接口是不是有效的接口,此时的请求方式是OPTIONS的请求方式,因此必须保证Token拦截器类在Options预处理请求时通知"OK"!

public class Authentication implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        System.out.println(request.getHeader("Authorization"));
        return TokenUtils.verifyToken(request.getHeader("Authorization"));

        // 前端请求拦截器
        //axios.interceptors.request.use(config => {
        //        config.withCredentials = true;// 允许携带token ,这个是解决跨域产生的相关问题
        //        config.headers.Authorization = localStorage.getItem("token");
        //        return config
        //}, error => {
        //        return Promise.reject(error)
        //    }
        //);
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值