• vue-cli3.x中使用axios发送请求,配合webpack中的devServer编写本地mock数据接口(get/post/put/delete)


    vue-cli3.x中使用axios发送请求,配合webpack中的devServer编写本地mock数据接口(get/post/put/delete)

    手把手式笔记

    Axios配置

    1. 安装 axios
    npm install axios
    
    1. main.js同级目录新建axios配置文件setaxios.js
    import axios from 'axios'
    // import store from './store' //vuex
    // import router from './router' //路由
    
    export default function setAxios() {
        //拦截request请求
        axios.interceptors.request.use(
            config=>{
                console.log(config.data);
                return config;
            }
        )
    
        //拦截response回调
        axios.interceptors.response.use(
            response=>{
                if(response.status===200){
                    const data=response.data
                    // if (data.code === 400){
                    //     //登录过期,权限不足
                    //     console.warn("登陆过期");
                    //     //清除token
                    //     store.commit('setToken','')
                    //     window.localStorage.removeItem('token')
                    //     //跳转登录
                    //     router.replace({
                    //         path:"/login"
                    //     })
                    // }
                    return data;
                }
                return response;
            }
        )
    }
    
    1. main.js中引入axios与其配置文件
    import axios from 'axios'
    import setaxios from './setaxios'
    
    //Vue全局挂载axios
    Vue.prototype.$http=axios
    //设置baseUrl
    axios.defaults.baseURL = '/api'
    

    devServer中配置本地mock数据接口(vue.config.js文件中)参考webpack中文文档

    module.exports = {
        publicPath: './',
        outputDir: 'dist',
        assetsDir: 'static',
        configureWebpack: {
            devServer: {
                contentBase: './build',//项目基本访问目录
                host: 'localhost',//服务器ip地址
                port: 8088,//端口
                open: true, //自动打开页面
                hot: true,//模块热替换
                hotOnly: true,//只有热更新不会刷新页面
                //mock数据接口部分 关键部分
                before(app) {
                    const bodyParser = require('body-parser')
                    app.use(bodyParser.json())  //通过bodyParser获取req.body)
                    
                    /**
                    *   testGet
                    */
                    app.get('/api/test/get',(req,resp)=>{
                        console.log(req.query);
    
                        resp.json({
                            "code":111,
                            "msg":"get测试成功"
                        })
                    })
    
    
                    /**
                     * testPost
                     */
                    app.post('/api/test/post', (req, resp) => {
                        console.log(req.body);
    
                        resp.json({
                            "code": 123,
                            "msg": "post测试成功"
                        })
                    })
    
                    /**
                     * testPut
                     */
                    app.put('/api/test/put', (req, resp) => {
                        console.log(req.body)
                        resp.json({
                            "code": 123,
                            "msg": "put测试成功"
                        })
                    })
    
                    /**
                     * testDelete
                     */
                    app.delete("/api/test/delete",(req,resp)=>{
                        console.log(req.body);
    
                        resp.json({
                            "code":666,
                            "msg":"delete测试成功"
                        })
                    })
                }
            }
        }
    }
    

    通过上述配置操作即可完成本地mock数据接口编写,接下来是axios发送http请求测试示例

    restful风格接口axios发送请求示例 参考axios中文文档

      methods: {
        sendGet: function() {
          this.$http
            .get("/test/get", {
              params: {
                param1: "get字符串",
                param2: 13131
              }
            })
            .then(res => {
              console.log(res);
            });
        },
        sendPost: function() {
          this.$http
            .post("/test/post", {
              param1: "post字符串",
              param2: 13131
            })
            .then(res => {
              console.log(res);
            });
        },
        sendPut: function() {
          this.$http
            .put("/test/put", {
              param1: "put字符串",
              param2: 13131
            })
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
            });
        },
        sendDelete: function() {
          this.$http
            .delete("/test/delete", {
              data: {
                param1: "delete字符串",
                param2: 13131
              }
            })
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    

    完整测试demo(Test.vue)

    <template>
      <div>
        <h2>HTTP-Request</h2>
        <button @click="sendGet()">GET</button>
        <span>&emsp;&emsp;</span>
        <button @click="sendPost()">POST</button>
        <span>&emsp;&emsp;</span>
        <button @click="sendPut()">PUT</button>
        <span>&emsp;&emsp;</span>
        <button @click="sendDelete()">DELETE</button>
        <hr />
      </div>
    </template>
    
    <script>
    export default {
      name: "testPage",
      data() {
        return {};
      },
      methods: {
        sendGet: function() {
          this.$http
            .get("/test/get", {
              params: {
                param1: "get字符串",
                param2: 13131
              }
            })
            .then(res => {
              console.log(res);
            });
        },
        sendPost: function() {
          this.$http
            .post("/test/post", {
              param1: "post字符串",
              param2: 13131
            })
            .then(res => {
              console.log(res);
            });
        },
        sendPut: function() {
          this.$http
            .put("/test/put", {
              param1: "put字符串",
              param2: 13131
            })
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
            });
        },
        sendDelete: function() {
          this.$http
            .delete("/test/delete", {
              data: {
                param1: "delete字符串",
                param2: 13131
              }
            })
            .then(res => {
              console.log(res);
            })
            .catch(err => {
              console.log(err);
            });
        }
      }
    };
    </script>
    

    示例效果图


    参考文档

    webpack中文文档

    Axios中文文档

    如有不妥,不解之处,请滴滴我,或在评论区留言

  • 相关阅读:
    奇虎360安全牛人全球挑战赛无线部…
    C经典之14-双向链表存储1-10---ShinePans
    linux杂谈(十五):ftp的企业应用级的配置(二)
    Cocos2d-x 3.0心得(01)-图片载入与混合模式
    Windows装10gRAC须要注意的几个要点(怎样解决PRKH-1010和PRKR-1062的错误)
    query多选下拉框插件 jquery-multiselect(改动)
    SICP 习题 (1.42)解题总结
    电话号码 【trie树】
    hdu 3854 Glorious Array(线段树or树状数组)
    【转载】CGLib动态代理原理及实现
  • 原文地址:https://www.cnblogs.com/roseAT/p/11228369.html
Copyright © 2020-2023  润新知