博客
关于我
vue 异步网络请求 axios 【实用教程】
阅读量:775 次
发布时间:2019-03-24

本文共 2937 字,大约阅读时间需要 9 分钟。

安装

安装axios可以通过以下命令执行:

npm install axios --save-dev

配置

在项目根目录下创建axios.js文件,并添加如下配置:

import axios from 'axios';// 设置默认请求头axios.defaults.baseURL = 'https://api.example.com';axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';// 添加请求拦截器axios.interceptors.request.use(function (config) {    const publicPath = [/^\/public/, /^\/login/];    let isPublic = false;    publicPath.map(path => {        isPublic = isPublic || path.test(config.url);    });    const token = sessionStorage.getItem('token');    if (!isPublic && token) {        config.headers.Authorization = 'Bearer ' + token;    }    if (config.method === 'get' && config.params) {        const keys = Object.keys(config.params);        let url = config.url;        for (let key of keys) {            url += `${key}=${encodeURIComponent(config.params[key])}&`;        }        url = url.substring(0, url.length - 1);        config.params = {};    }    config.url = url;    return config;}, function (error) {    return Promise.reject(error);});// 添加响应拦截器axios.interceptors.response.use(function (response) {    return response;}, function (error) {    return Promise.reject(error);});

src/main.js中导入axios并赋值:

import axios from 'axios';import './axios.js';Vue.prototype.$http = axios;

get 请求

如何发送get请求:

this.$http({    method: 'get',    url: 'http://jsonplaceholder.typicode.com/users',    params: {        id: 1    }}).then(res => {    this.user1 = res.data;});

post 请求

如何发送post请求:

this.$http({    method: 'post',    url: 'https://jsonplaceholder.typicode.com/posts',    data: {        name: '朝阳',        sex: '男'    }}).then(res => {    this.$message.success(res.msg);});

并发请求

如何实现并发请求:

function getUserAccount() {    return this.$http.get('/user/12345');}function getUserPermissions() {    return this.$http.get('/user/12345/permissions');}this.$http.all([getUserAccount(), getUserPermissions()])    .then(this.$http.spread(function (acct, perms) {        // 所有请求都完成后执行此回调    }));

获取图片

如何获取图片文件:

this.$http({    method: 'get',    url: 'http://bit.ly/2mTM3nY',    responseType: 'stream'}).then(function (response) {    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'));});

请求配置

完整的请求配置示例:

{    url: '/user',    method: 'get',    baseURL: 'https://some-domain.com/api/',    headers: {        'X-Requested-With': 'XMLHttpRequest'    },    params: {        ID: 12345    },    paramsSerializer: function (params) {        return Qs.stringify(params, { arrayFormat: 'brackets' });    },    data: {        firstName: 'Fred'    },    timeout: 1000,    withCredentials: false,    auth: {        username: 'janedoe',        password: 's00pers3cret'    },    responseType: 'json',    responseEncoding: 'utf8',    maxContentLength: 2000,    proxy: {        host: '127.0.0.1',        port: 9000,        auth: {            username: 'mikeymike',            password: 'rapunz3l'        }    }}

转载地址:http://qqmkk.baihongyu.com/

你可能感兴趣的文章
nexus上传jar
查看>>
Nexus指南中的更新强调集成和透明度的重要性
查看>>
Nexus指南已经发布
查看>>
Nexus(1):Nexus的安装与配置
查看>>
NFinal学习笔记 02—NFinalBuild
查看>>
NFS
查看>>
nfs mount 故障 mount.nfs: access denied by server while mounting 10.0.100.208:/backup_usb
查看>>
NFS Server及Client配置与挂载详解
查看>>
NFS 服务配置篇
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>
NFS安装配置
查看>>
NFS服务器配置-服务启动与停止
查看>>
NFS的安装以及windows/linux挂载linux网络文件系统NFS
查看>>
NFS的常用挂载参数
查看>>
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>