vue模拟数据——json-server+axios(简单使用)+代理

json-server

  1. 建立模拟数据:在src同级目录下创建文件:db.json

  2. 首先先下载包

     npm install json-server -g
    
  3. 打开集成终端,设置端口,这个端口是你脚手架的端口号,方便代理

     json-server db.json --port 8080
    

在这里插入图片描述

  1. 打开package.json文件 然后在scripts中配置一个mock,这个端口号是访问你虚拟数据的端口号:

     "mock": "json-server db.json --port 3003"
    
      "scripts": {
     	"dev": "webpack-dev-server --inline --progress --config 	
     	 build/webpack.dev.conf.js",	 		    
     	"start": "npm run dev",
         "build": "node build/build.js",
         "mock": "json-server db.json --port 3003"
    

},

  1. 执行 npm run dev
    在这里插入图片描述
    也可以直接访问 http://localhost:3003/
    在这里插入图片描述

发现 http://localhost:3003/
http://localhost:8080/是一样

6. 书写测试代码,你可以直接但APP.vue上测试,或者删掉重新配置,记得在main.js中y引入文件并直接渲染 render:(h) =>h(文件名)
这时候要才用多线程,也就是你要多开个终端,先关掉之前的终端,因为刚刚在json-server db.json --port 8080,8080端口被使用了,为了防止端口占用,全部关掉。然后重新一个启动json-server,一个启动项目npm run dev

<template>
 <div id="app">
   {{login}}
 </div>

</template>
<script>
export default {
    created: function () {
    this.$http.get('http://localhost:8080/login')
    .then((res) => {
      this.login = res.data
    }, (err) => {
      console.log(err)
    }) 
  },
  data () {
    return {
    login:[]
    }
  }
}
</script>

代理服务器

简单理解就是当你访问/api时你会映射到你的虚拟数据http://localhost:3003,
就是/api是http://localhost:3003的代言人!!!!

  1. 设置config/index.js 的proxyTable
 proxyTable: {
      '/api/': {
        target: 'http://localhost:3003', //将http://localhost:3003映射到/api
        changeOrigin: true,   //是否跨域
        pathRewrite: { 
          '^/api': '',   // 因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'
        }
      }
    },

http://localhost:8080/api将会映射访问到http://localhost:3003页面,起到一个代理作用

  1. 修改请求的url地址
export default {
    created: function () {
    this.$http.get('/api/login')
    .then((res) => {
      this.login = res.data
    }, (err) => {
      console.log(err)
    }) 
  },
  data () {
    return {
    login:[]
    }
  }
}
</script>
  1. 重新启动 npm run dev
    在这里插入图片描述
  2. 请求对应数据也要加/api/
    eg: 在这里插入图片描述

axios

  1. 首先下包

     npm install axios
    
  2. 在main.js中引入

     var axios = require('axios'); 
    
  3. 发出请求


axios.get('/api/dataInData')
.then(function(response){
    console.log(response);
}).catch(function(response){
    console.log(response);
});

在这里插入图片描述
荧光笔就是获取的数据
可以看一下大佬的笔记和项目学习
github项目
博客

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值