Vue(二十一)使用express模拟接口数据

1.下载express

...

2.使用vue-cli下载好项目文件

...

3.找到文件 build - webpack.dev.conf.js

‘use strict‘
const utils = require(‘./utils‘)
const webpack = require(‘webpack‘)
const config = require(‘../config‘)
const merge = require(‘webpack-merge‘)
const path = require(‘path‘)
const baseWebpackConfig = require(‘./webpack.base.conf‘)
const CopyWebpackPlugin = require(‘copy-webpack-plugin‘)
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)
const FriendlyErrorsPlugin = require(‘friendly-errors-webpack-plugin‘)
const portfinder = require(‘portfinder‘)

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

/**
 * 使用express框架启动一个服务器
 */
var express = require(‘express‘)
var app = express()
//1.读取数据
var appData=require(‘../static/json/table.json‘);
var businessNum=appData.businessNum;
var recruitingNum=appData.businessNum;
var customerData=appData.businessNum;

//2.使用expresss配置路由,指定接口请求
var apiRoutes=express.Router(); //定义一个路由

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: ‘warning‘,
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    },
    before(apiRoutes) {
      apiRoutes.get(‘/api/businessNum‘, (req, res) => {
        res.json({
          // 这里是你的json内容
          errno: 0,
          data: businessNum
        })
      });
      apiRoutes.get(‘/api/recruitingNum‘, (req, res) => {
        res.json({
          // 这里是你的json内容
          errno: 0,
          data: recruitingNum
        })
      });
      apiRoutes.get(‘/api/customerData‘, (req, res) => {
        res.json({
          // 这里是你的json内容
          errno: 0,
          data: customerData
        })
      })
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      ‘process.env‘: require(‘../config/dev.env‘)
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: ‘index.html‘,
      template: ‘index.html‘,
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, ‘../static‘),
        to: config.dev.assetsSubDirectory,
        ignore: [‘.*‘]
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

4.在页面中发送axios请求(先在main.js中引入axios)

...
import axios from ‘axios‘
...
/* 全局引入axios */
Vue.prototype.$http = axios

5.在页面中请求数据

  created () {
        this.$http.get(‘/api/businessNum‘).then(response => {
            console.log(response)
        }).catch(response => {
            console.log(response)
        })
    }

6.页面加载返回数据信息

原文地址:https://www.cnblogs.com/yulingjia/p/8794396.html

时间: 2024-07-30 05:31:56

Vue(二十一)使用express模拟接口数据的相关文章

vue项目中使用mockjs模拟接口返回数据

Mock.js 是一个模拟数据生成器,利用它,可以拦截ajax请求,直接模拟返回数据,这样前后端只要约定好数据格式,前端就不需要依赖后端的接口,可以直接使用模拟的数据了. 网上介绍mock的教程也较多,不过大多数看的比较模糊.其实使用起来非常简单,这里介绍在Vue工程中使用Mockjs,并且实现开发和生产配置化. 一.安装 cnpm install --save-dev mockjs 二.引入 为了只在开发环境使用mock,而打包到生产环境时自动不使用mock,我们可以在env中做一个配置 //

在Vue中使用mock模拟接口数据

一.在配置文件里添加新的代理mock模拟数据的地址(如下) 二.使用接口地址 原文地址:https://www.cnblogs.com/exclusiveMemory/p/9842515.html

Vue 使用 Vuex 和 axios 获取接口数据

修改原型链 //main.js import axios from 'axios'; Vue.prototype.$ajax = axios; //修改原型链 // .vue文件 methods:{ getData(){ this.$ajax.get('https://easy-mock.com/mock/5d41481656e5d340d0338e4b/shop/commodity') .then(res => { console.log(res) }).catch(err => { con

11. react 基础 使用charles 模拟接口数据

charles参考文档 charles官网 模拟数据 模拟 axios 请求的数据 eg: 1. 编写 axios 请求 axios.get('/api/xxx') .then(()=>{alert('succ')}) .catch(()=>{alert('err')}) 2. 在 Desktop (桌面) 创建一个xxx.json文件 cd ~/Desktop touch xxx.json 3. 编辑 xxx.json ["zone", "hoo"]

justinmind夜话:数据母板系列视频教程之原型设计二十一条军规

案例描述:使用数据母板实现原型设计二十一条军规 知识点: 数据母板 效果图: 本站在线效果预览:(原型文件) 原型下载地址:数据母板原型设计二十一条军规 .vp  数据母板原型设计二十一条军规.html 在线视频: 实现步骤:

云计算设计模式(二十一)——Sharding分片模式

云计算设计模式(二十一)——Sharding分片模式 将一个数据存储到一组水平分区或碎片.存储和访问大量数据时,这个模式可以提高可扩展性. 背景和问题 由一个单一的服务器托管的数据存储区可能会受到以下限制:•存储空间.一种数据存储为一个大型云应用可以预期含有数据量巨大,可以随着时间的推移显著增加.服务器通常提供的磁盘存储仅是有限的,但它可以是能与较大的取代现有的磁盘,或者添加另外的磁盘的机器作为数据量的增加.然而,由此,不能够容易地增加一个给定的服务器上的存储容量的系统最终将达到一个硬限制.•计

vue中用mock制造模拟接口(本文主要解决坑),一定要看完哦

最近新入职一家公司,后端造接口速度很慢,想来想去还是搞一套模拟接口,来满足开发需求,有人会问,我造一个死数据不就可以了吗?或者说,后端数据结构都没出来,字段我怎么定? 问这个问题的人不奇怪,我之前也有这种疑问,mock造出来的数据是动态的.前端完全可以自己造数据结构,后端根据这个做一个模型就可以了,谁叫他们慢,字段嘛,实在要修改,他们确实不好改,前端改改就完事了;下面我将跟大家说说最近玩vue+mockjs的心得, vue的项目搭建我就不多说了,有自己用vue-cli创建的,也有直接用webpa

App开发:模拟服务器数据接口 - MockApi

App开发:模拟服务器数据接口 - MockApi 为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现MockApi. 需求概述 在app开发过程中,在和服务器人员协作时,一般会第一时间确定数据接口的请求参数和返回数据格式,然后服务器人员会尽快提供给客户端可调试的假数据接口.不过有时候就算是假数据接口也来不及提供,或者是接口数据格式来回变动--很可能是客

vue 接口数据(数组)语句

当接口数据已经有数组时,其实更简单,直接调出数据中的数组,使用数据中的名称. 1 <div v-for="item in listarr" 2 :class="{red:item.runStatus==1,blue:item.runStatus==2,orange:item.runStatus==3}">//判断item.runStatus的值,值不同class不同 3 <i class="glyphicon text-center gl