在uniapp的项目里面,怎么写入模拟接口数据?现在使用node服务实现几个模拟接口,当然是用mock也是可以的哦,方法有很多种,目的只有一个,就是能够娴熟的应用在项目场景里面。
1:json数据
写在data底下的js里面
json.js
let data = { //这里放数据 "categories": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "data": [ 3, 2, 4, 4, 5 ] } module.exports = { data: data }
json1.js
let data = { "echatX": [ "2019-07-02", "2019-07-03", "2019-07-04", "2019-07-05", "2019-07-06", "2019-07-07", "2019-07-08", "2019-07-09", "2019-07-10", "2019-07-11", "2019-07-12", "2019-07-13", "2019-07-14", "2019-07-15" ], "echatY": [ 120,121,123,123,125,127,128,129,120,123,122,126,129,122 ], "echatY2": [ 60,64,63,63,65,67,68,69,61,66,65,68,69,65 ], "echatY3": [ 60,64,63,63,65,67,68,69,161,66,65,68,169,165 ] } module.exports = { data: data }
json3.js
let data = { "first":[ {"name":"王小婷","nick":"祈澈菇凉"}, {"name":"安安","nick":"坏兔子"}, {"name":"编程微刊","nick":"简书"} ] } module.exports = { data: data }
以上是自己随意造的数据啊不要过于在意了
2:在项目底下新建一个server文件夹,用来写我的node服务。
server.js
const http = require("http"); const data = require("../data/json"); const data2 = require("../data/json1"); const data3 = require("../data/json3"); const server = http.createServer((req, res) => { //解决跨域问题 res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.setHeader('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); res.writeHead(200, { 'Content-Type': 'application/json' }); if(req.url === '/'){ res.end(JSON.stringify(data.data)) } if(req.url === '/data'){ res.end(JSON.stringify(data2.data)) } if(req.url === '/data3'){ res.end(JSON.stringify(data3.data)) } }); server.listen(3000, () => { console.log("server is running!") })
3:运行
在编辑器的内置终端里面,进入文件夹server,启动刚刚写的服务
cd server
$ node --inspect server.js
4:打开浏览器,就可以看到模拟接口实现啦
5:测试一下,就用这个接口吧http://localhost:3000/data3
<template> <view> <view class="uni-padding-wrap uni-common-mt" v-for="item in itemList"> <span>{{item.name}}</span> <span>{{item.nick}}</span> </view> </view> </template> <script> export default { data() { return { itemList: [] } }, onLoad() { this.getList(); }, methods: { getList() { uni.request({ url: 'http://localhost:3000/data3', success: (res) => { console.log(res.data); this.itemList =res.data.first; } }); } } } </script> <style> .img { width: 500upx; height: 500upx; margin: 0 95upx; } </style>
好的,测试成功了,数据也可以显示啦