Ajax请求模块

 安装依赖 npm install --save axios

1. 封装ajax请求模块(src/api/ajax.js)

 axios请求成功后返回的是response, 然后通过response.data获取数据
 封装ajax函数请求成功后直接返回data数据

 /**
 * ajax请求函数模块
 * 参数: url  路径
 *      data  地址栏参数
 *      type  请求方式,默认GET
 * 返回值: promise对象的data数据(response.data)
 */

import axios from 'axios'
export default function ajax(url, data = {}, type = "GET") {
    return new Promise(function (resolve, reject) {
        // 执行异步ajax请求
        let promise
        if (type === 'GET') {
            let dataStr = ''
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            promise = axios.get(url)
        } else {
            promise = axios.post(url, data)
        }
        promise.then(function (response) {
            // 成功调用resolve()
            resolve(response.data)
        }).catch(function (error) {
            // 失败失败reject()
            reject(error)
        })
    })
}

2. 发送请求模块(src/api/index.js)

 根据接口文档, 定义接口请求函数(项目中所有的请求都放在此文件里)

import ajax from './ajax'

// http://localhost:3000/position  参数类型null  GET      
export const reqUser = () => ajax(`/position`)

// http://localhost:3000/position/2,3  参数类型param   GET      
export const reqUser = (option) => ajax(`/position/${option}`)

//http://localhost:3000/shops?a=2&b=3   参数类型query    GET  
export const reqUser = (a, b) => ajax('/shops', {a, b})

// http://localhost:3000/login_pwd    参数name,pwd     POST
export const reqPwdLogin = ({name, pwd}) => ajax(BASE_URL+'/login_pwd', {name, pwd}, 'POST')

export const reqTest = (uid,number) => ajax('https://data.autohome.com.cn/rcm/automobile/lands',{uid,number})

3. 组件中调用请求模块函数获取数据

 先引入 import { reqTest } from "./api";
 然后在mounted中执行

async mounted() {
        const result = await reqTest(0,10)
        console.log(result.result.list)
    }

你可能感兴趣的:(Ajax请求模块)