vue中使用axios

來源:互聯網
上載者:User

標籤:export   baseurl   encode   cat   code   data   min   請求   create   

1.安裝axios

npm:

$ npm install axios -S

cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2.配置axios

在項目中建立api/index.js檔案,用以配置axios

api/index.js

import axios from ‘axios‘;let http = axios.create({  baseURL: ‘http://localhost:8080/‘,  withCredentials: true,  headers: {    ‘Content-Type‘: ‘application/x-www-form-urlencoded;charset=utf-8‘  },  transformRequest: [function (data) {    let newData = ‘‘;    for (let k in data) {      if (data.hasOwnProperty(k) === true) {        newData += encodeURIComponent(k) + ‘=‘ + encodeURIComponent(data[k]) + ‘&‘;      }    }    return newData;  }]});function apiAxios(method, url, params, response) {  http({    method: method,    url: url,    data: method === ‘POST‘ || method === ‘PUT‘ ? params : null,    params: method === ‘GET‘ || method === ‘DELETE‘ ? params : null,  }).then(function (res) {    response(res.data);  }).catch(function (err) {    response(err);  })}export default {  get: function (url, params, response) {    return apiAxios(‘GET‘, url, params, response)  },  post: function (url, params, response) {    return apiAxios(‘POST‘, url, params, response)  },  put: function (url, params, response) {    return apiAxios(‘PUT‘, url, params, response)  },  delete: function (url, params, response) {    return apiAxios(‘DELETE‘, url, params, response)  }}

這裡的配置了POST、GET、PUT、DELETE方法。並且自動將JSON格式資料轉為URL拼接的方式

同時配置了跨域,不需要的話將withCredentials設定為false即可

並且設定了預設頭部地址為:http://localhost:8080/,這樣調用的時候只需寫存取方法即可

3.使用axios

首先在main.js中引入方法

import Api from ‘./api/index.js‘;Vue.prototype.$api = Api;

然後在需要的地方調用即可

this.$api.post(‘user/login.do(地址)‘, {    "參數名": "參數值"}, response => {     if (response.message === undefined) {        this.$message.success(response);\\請求成功,response為返回參數     } else {        this.$message.error(response.message);\\請求失敗,response為失敗資訊     }});

vue中使用axios

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.