• Vue中使用Ajax与后台交互


    一、下载依赖包

    npm install --save axios

    二、封装 ajax 请求模块

    2.1 api/ajax.js

    /*
    ajax 请求函数模块
     */
    import axios from 'axios'
    
    export default function ajax (url = '', data = {}, type = 'GET') {
      return new Promise(function (resolve, reject) {
        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(response => {
          resolve(response.data)
        }).catch(error => {
          reject(error)
        })
      })
    }

    2.2 api/index.js

    /*
    与后台交互模块
     */
    import ajax from './ajax'
    
    /**
     * 根据经纬度获取位置详情
     */
    export const reqAddress = geohash => ajax('/api/position/' + geohash)
    
    /**
     * 获取食品分类列表
     */
    export const reqCategorys = () => ajax('/api/index_category')
    
    /**
     * 根据经纬度获取商铺列表
     */
    export const reqShops = ({longitude, latitude}) => ajax('/api/shops/', {longitude, latitude})
    
    /**
     * 获取一次性验证码
     */
    export const reqCaptcha = geohash => ajax('/api/position/' + geohash)
    
    /**
     * 用户名密码登陆
     */
    export const reqPwdLogin = (name, pwd, captcha) => ajax('/api/login_pwd', {name, pwd, captcha}, 'POST')
    
    /**
     * 发送短信验证码
     */
    export const reqSendCode = phone => ajax('/api/sendcode' + {phone})
    
    /**
     * 手机号验证码登陆
     */
    export const reqSmsLogin = (phone, code) => ajax('/api/logon_sms/', {phone, code}, 'POST')
    
    /**
     * 根据会话获取用户信息
     */
    export const reqUser = () => ajax('/api/userinfo')
    
    /**
     * 用户登出
     */
    export const reqLogout = () => ajax('/api/logout')

    三、配置代理

    proxyTable: {
        '/api': { // 匹配所有以 '/api' 开头的请求路径
            target: 'http://localhost:4000', // 代理目标的基础路径
            changeOrigin: true, // 支持跨域
            pathRewrite: { // 重写路径:去掉路径中开头的'/api'
                '^/api': ''
            }
        }
    }    
  • 相关阅读:
    简单的html5 File base64 图片上传
    PHP CURL POST
    PHP常用代码段:
    使用Sqlserver事务发布实现数据同步(转)
    几个SQL小知识(转)
    Sql语句摘要
    C#创建服务及使用程序自动安装服务,.NET创建一个即是可执行程序又是Windows服务的exe(转)
    说说C#的async和await(转)
    c#并发编程经典实例文摘
    [在职软件工程]数据挖掘-概念与技术
  • 原文地址:https://www.cnblogs.com/mxsf/p/10877704.html
Copyright © 2020-2023  润新知