React系列學習筆記:7.簡單api服務器

前言

本節我們將創建一個簡單的后端API服務器,以便我們的應用進行相應的測試。僅僅只用express創建一個服務器就行,將用到幾個express中間件:

  • body-parser:用于服務器body的內容解析

服務器

actions/loadInfo.js
一個簡單的時間加載信息,用于測試。非常簡單,僅僅就是返回一個Promise的信息

export default function loadInfo(){
  return Promise.resolve({
    message:'This came from the api server',
    time:Date.now()
  })
}

以后因為還要添加其他API接口,所以這里我們要編寫一個針對不同的url訪問不同API的能用函數utils/url.js

export default function mapUrl(availableActions={},url=[]){
  //錯誤url或沒有api接口時反回錯誤
  const notFound = {action:null,params:[]}
  if (url.length === 0 || Object.keys(availableActions).length === 0 ){
    return notFound
  }

  const reducer = (prev, current) => {
    if (prev.action && prev.action[current]) {
      return {action: prev.action[current], params: []}; // go deeper
    } else {
      if (typeof prev.action === 'function') {
        return {action: prev.action, params: prev.params.concat(current)}; // params are found
      } else {
        return notFound;
      }
    }
  };

  const actionAndParams = url.reduce(reducer,{action:availableActions,params:[]})

  return (typeof actionAndParams.action === 'function') ? actionAndParams : notFound

}

api.js
服務器入口文件,通過上面的mapUrl函數簡單的將urlaction對應起來。

import express from 'express';
import bodyParser from 'body-parser';

import mapUrl from './utils/url'
import * as actions from './actions'
import config from '../config/appConfig'

const app = express()


app.use(bodyParser.json());

app.use((req,res) =>{


  //比如請求url為/loadInfo/param1/param2?user=John 結果為['loadInfo','pamam1','param2']
  const splitteUrlPath = req.url.split('?')[0].split('/').slice(1)
  const {action, params} = mapUrl(actions,splitteUrlPath)

  if(action){
    action(req,params)
      .then((result) => {
        if (result instanceof Function){
          result(req)
        }else{
          res.json(result)
        }
      },(reason) => {
          if(reason && reason.redirect){
            reason.redirect(reason.redirect)
          }else{
            res.status(reason.status || 500).json(reason)
          }
      })
  }else{
    res.status(404).end('Not Found')
  }
})

if(config.apiPort){
  app.listen(config.apiPort,(err)=>{
    if (err) { console.log(err)}
    console.log('Api server listen at %s', config.apiPort)
  })
}

最后在package.json里添加啟動命令,然后訪問http://localhost:3030看到反回的時間,說明我們的服務器正常運行

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容