axios in vue

Keywords: axios Vue npm JSON

axios in vue

1.install axios

npm: $ npm install axios -S

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

2. Configure axios

//Create a new api/index.js file in the project to configure axios

api/index.js

//Copy code
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);
  }).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)
  }
}

//Here, POST, GET, PUT and DELETE methods are configured. And automatically convert JSON format data to URL splicing

//At the same time, cross domain is configured. If not needed, set withCredentials to false

//The default header address is set to: http://localhost:8080 /, so that only the access method needs to be written when calling

3. Use axios

Note: the PUT request will send two requests by default. The first pre check request does not contain parameters, so the backend cannot restrict the PUT request address

First, introduce the method in main.js

import Api from './api/index.js';
Vue.prototype.$api = Api;
Then call it where you need it

Copy code
 This. $API. Post ('user / login. Do (address) '{
    Parameter name: parameter value
}, response => {
     if (response.status >= 200 && response.status < 300) {
        console.log(response.data); \ \ the request is successful, and response is the success information parameter
     } else {
        console.log(response.message); \ \ request failed, response is failure message
     }
});
This article is from: https://www.cnblogs.com/hackyo/p/7992174.html

Posted by neerav on Thu, 26 Mar 2020 10:04:12 -0700