Article reference
http://blog.csdn.net/sinat_17775997/article/details/54915257
Since Vue was updated to 2.0, the official no longer updates vue-resource; currently mainstream Vue projects choose [axios](https://github.com/mzabriskie/axios) to complete ajax requests
install axios
cnpm install axios --save
Basic usage of get request
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Basic usage of post request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Execute multiple requests simultaneously
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete }));
How to make axios cross domain
import api from './apiList'; import axios from 'axios'; import querystring from 'querystring'; import {server_config} from '../config/config.js'; var serverPort = server_config.URL + ":" + server_config.PORT; const instance = axios.create({ baseURL: serverPort, timeout: 20000, validateStatus:function(status){ return status < 500; }, headers: { // Cross-domain request this configuration can not be less "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", 'Accept': 'application/json' } }); //Send the request through axios export default { /** * @param urlKey corresponds to the urlkey in the API * @param paramObj send the parameter object passed by ajax * @returns {promise} returns the promise object * @example axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); */ get:function(urlKey, paramObj){ var apiStr = serverPort + api[urlKey]; return axios.get(apiStr,paramObj); }, /** * @param urlKey corresponds to the urlkey in the API * @param paramObj send the parameter object passed by ajax * @returns {promise} returns the promise object * @example axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (response) { console.log(response); }); */ post:function(urlKey,paramObj){ var apiStr = serverPort + api[urlKey]; return instance.post(apiStr,querystring.stringify(paramObj)); }, }
Note: Use axios.create() to create an axios object, then configure cross-domain header information, and use this object for all subsequent requests .