2

build/webpack.dev.conf.js 文件里的修改

  1. 在const portfinder = require('postfinder')后添加

    const express = require('express')
    const app = express()
    const appData = require('../data.json')//加载本地的json文件
    const seller = appData.seller
    const goods = appData.goods
    const ratings = appData.ratings
    const apiRoutes = express.Router()
    app.use('/api',apiRoutes)
    
  2. 然后找到devServer,在他的里面插入一下代码:

    before(app){
        app.get('/api/seller',(reg,res)=>{
            res.json({
                errno: 0,
                data: seller
            })//接口返回json数据,上面配置的数据seller就复制给data请求后调用
        }),
        app.get('/api/goods',(reg,res) => {
            res.json({
                errno: 0,
                data: goods
            })
        }),
        app.get('api/ratings',(reg,res) => {
            res.json({
                errno: 0,
                data: ratings
            })
        })
    }
    
  3. 请求访问(.vue 文件里的调用)

    this.$axios.get('/api/home', {
         params: {
             categoryId: categoryId
         }
    })
    .then(response => {     //这里要使用箭头函数,使用ES5的写法  this是undefined
        console.log(response);
     })
     .catch(error => {
         console.log(error)
         console.log(this);
     })
  4. 最后重启项目即可 npm run dev

参考链接:https://my.oschina.net/lpcysz...


懒惰的小白
41 声望0 粉丝