1. 程式人生 > >使用 node 模擬請求接口

使用 node 模擬請求接口

rom images body ons uil expr wid https pre

使用 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
        })
      })
    }
技術分享圖片 技術分享圖片
三、使用 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 模擬請求接口