vue-cli中模拟数据的两种方法

我所使用的是新版vue-cli

首先进行所需插件的安装,vue-resource,json-server,proxyTable.vue

目录结构如图

在main.js中引入vue-resource模块,Vue.use(vueResource).webpack

1.使用json-server(不能用post请求)

接下来找到build目录下的webpack.dev.conf.js文件,在const portfinder = require('portfinder')后面引入json-server.web

/*引入json-server*/
const jsonServer = require('json-server')
/*搭建一个server*/
const apiServer = jsonServer.create()
/*将db.json关联到server*/
const apiRouter = apiServer.router('db.json')
const middlewares  = jsonServer.defaults()\
apiServer.use(apiRouter)
apiServer.use(middlewares)
/*监听端口*/
apiServer.listen(3000,(req,res)=>{
  console.log('jSON Server is running')  
})
复制代码

如今重启服务器后浏览器地址栏输入localhost:3000能进入以下页面则说明json server启动成功了ajax

如今找到config文件夹下的index.js文件,在dev配置中找到proxyTable:{} 并在其中配置vue-cli

'/api':{
    changeOrigin:true, //示范容许跨域
    target:"http://localhost:3000", //接口的域名
    pathRewrite:{
        '^/api':'' //后面使用重写的新路径,通常不作更改
    }
}
复制代码

如今能够使用localhost:8080/api/apiName 请求json数据了express

在项目中经过resource插件进行ajax请求json

data (){}前使用钩子函数created:function(){
    this.$http.get('/api/newsList')
        .then(function(res){
            this.newsList = res.data //赋值给data中的newsList
        },function(err){
            console.log(err)
        })
}
复制代码

2.使用express(能够使用post请求)

在项目中新建routes文件并在其中新建api.js,内容以下:api

const express = require('express')
const router = express.Router()
const apiData = require('../db.json')

router.post('/:name',(req,res)=>{
    if(apiData[req.params.name]){
        res.json({
            'error':'0',
            data:apiData[req.params.name]
        })
    }else{
        res.send('no such a name')
    }
})

module.exports = router
复制代码

接下来找到build目录下的webpack.dev.conf.js文件,在const portfinder = require('portfinder')后面引入express,以下:跨域

const express = require('express')
 const app = express()
 const api = require('../routes/api.js')
 app.use('/api',api)
 app.listen(3000)
复制代码

如今找到config文件夹下的index.js文件,在dev配置中找到proxyTable:{} 并在其中配置浏览器

'/api':{
    changeOrigin:true, //示范容许跨域
    target:"http://localhost:3000", //接口的域名
    pathRewrite:{
        '^/api':'/api' //后面使用重写的新路径,通常不作更改
    }
}
复制代码

重启以后,即可以post请求访问数据了.

相关文章
相关标签/搜索