vue使用axios发送ajax(跨域处理)

文章参考

http://blog.csdn.net/sinat_17775997/article/details/54915257

 

自从 Vue 更新到 2.0 之后,官方就不再更新 vue-resource;目前主流的 Vue 项目,都选择 [axios](https://github.com/mzabriskie/axios) 来完成 ajax 请求

 

安装axios

 

cnpm install  axios --save

 

 

get请求的基本用法

 

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

 

 

 

post请求基本用法

 

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });

 

 

同时执行多个请求

 

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
    }));

 

 

如何让axios跨域

 

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: {
        // 跨域请求 这个配置不能少
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        'Accept': 'application/json'
    }
});

//通过axios发送请求
export default {
    /**
     * @param urlKey 对应API 中的urlkey
     * @param paramObj  发送ajax 传递的参数对象
     * @returns {promise} 返回promise对象
     * @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 对应API 中的urlkey
     * @param paramObj  发送ajax 传递的参数对象
     * @returns {promise} 返回promise对象
     * @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));
    },
}

 

 

备注:使用axios.create()创建一个axios对象,然后配置跨域的头信息,后面所有的请求,全部使用该对象

 

 

展开阅读全文

没有更多推荐了,返回首页