使用 node 模拟请求接口

栏目: Node.js · 发布时间: 6年前

内容简介:使用在

使用 Vue 写项目肯定会遇到一个问题,如何模拟服务端请求数据,那这就需要用到 node.js 了。这篇我们讲解一下如何使用 node.js 模拟服务器端请求数据。

一、 初始化并创建一个项目

vue init webpack-simple node-demo cd node-demo npm i cnpm i vuex axios -S

二、编写接口

build 文件下的 webpack.dev.conf.js 文件中加入

express 基于 node.js 后端框架,负责路由,业务逻辑,数据库操作,页面和数据响应。

即架构中的业务层,对前端的请求进行响应,需要数据库的拉取数据库内容,需要判断处理的返回处理结果,请求页面文件的返回html文件

const express = require('express')
// 通过 node 访问模拟数据
const app = express();
// 使用 express 框架启动一个服务器
// 1. 读取文件
var appData = require('../data.json')
var seller = appData.seller
var goods = appData.goods
var ratings = appData.ratings

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

// 暴露 API 接口
app.use('/api',apiRoutes)
复制代码

build 文件下的 webpack.dev.conf.js 文件中的 devServer 中加入

// 添加接口数据
    before(app){
      // 配置请求路由和响应
      app.get('/api/seller', (req, res) => {
        res.json({
          errno: 0, //错误码
          data: seller
        })
      })

      app.get('/api/goods', (req, res) => {
        res.json({
          errno: 0, //错误码
          data: goods
        })
      })

      app.get('/api/ratings', (req, res) => {
        res.json({
          errno: 0, //错误码
          data: ratings
        })
      })
    }
复制代码

如下图:

使用 node 模拟请求接口

使用 node 模拟请求接口

三、使用 axios 请求数据

在组件中直接请求数据就好了

<template>  
    <div class="seller">
        <h1>{{seller}}</h1>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data(){
        return {
            seller:''
        }
    },
    mounted(){
        //请求地址
        axios.get('/api/seller').then(resp => {
            this.seller = resp.data.data.name
        })
    }
}
</script>复制代码

以上所述就是小编给大家介绍的《使用 node 模拟请求接口》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Elements of Statistical Learning

The Elements of Statistical Learning

Trevor Hastie、Robert Tibshirani、Jerome Friedman / Springer / 2009-10-1 / GBP 62.99

During the past decade there has been an explosion in computation and information technology. With it have come vast amounts of data in a variety of fields such as medicine, biology, finance, and mark......一起来看看 《The Elements of Statistical Learning》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具