程序员

在AngularJs中使用axios进行api的访问

2020-12-25  本文已影响0人  永远爱你ol

在工作中前端框架用到了AngularJs,对于前后端分离的项目来说,想必axios用的应该还是蛮多的,所以接下来分享一下axios是如何访问api的。

上传文件时的使用:

upload(api: string, file: any) {
    return new Promise((res, rej) => {
      let params = new FormData()
      for (const key of Object.keys(file)) {
        params.append(key, file[key])
      }
      axios.post(this.uri + api, params, { headers: { 'Content-Type': 'multipart/form-data' } })
        .then(function (response) {
          res(response);
        })
        .catch(function (error) {
          rej(error);
        });
    });
  }

get方法带参数时的使用:

 sendMessage(api: string, address: string, url: string) {
    return new Promise((res, rej) => {
      axios.get(this.uri + api, { params: { 'address': address, 'url': url } })
        .then(function (response) {
          res(response);
        })
        .catch(function (error) {
          rej(error);
        });
    });
  }

post方法带参数时的使用:

sendMessage(api: string, address: string, url: string) {
    const data = {
      "address": address,
      "url": url
    }
    return new Promise((res, rej) => {
      axios.post(this.uri+api, data)
        .then(function (response) {
          res(response);
        })
        .catch(function (error) {
           rej(error);
        })
    });
  }
上一篇 下一篇

猜你喜欢

热点阅读