用Node+Typescript+Express书写get请求获取数据与查询的接口

准备JSON文件

在package.json同级下建

名为data的文件夹,里面建

你要的xxx.json文件和汇总的xxx.ts文件

  • 我建了posts.json,data.ts
  • json里是数组对象的形式

代码

//posts.json,内容是随便写的,按照key,value方式就可
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat ",
"body": "nnostrum rerum est autem sunt rem eveniet architecto",
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "nqui aperiam non debitis possimus qui neque nisi nulla",
}
]

引入.json文件不能识别,在tsconfig.json里配置

  • 全局搜索esModuleInterop的下面加
  • “resolveJsonModule”: true,
    //data.ts
    import posts from './posts.json'
    export class DataStore{
    static posts = posts;
    }

server.ts里配置

  • apiGetPosts,apiGetPostsDetail是进行了模块化api,后面会说,不急。
    import express  from "express";
    import { apiGetPosts } from "./api/posts/apiGetPosts";
    import { apiGetPostsDetail } from "./api/posts/apiGetPostsDetail";

    const app = express()
    // routes
    app.get('/',(req,res,next)=>{ //http://localhost:8091/
    res.send('nho,oooooo')
    })
    app.get('/posts',apiGetPosts) //http://localhost:8091/post ,/xxx是名字可改
    app.get('/post/:id',apiGetPostsDetail)//http://localhost:8091/post/id,查询数据

    // 监听端口 前是打包部署后的,后面是默认的
    app.listen(process.env.PORT || 8091,()=>{
    console.log('Server started...')
    })

模块化api

在package.json同级下建

名为api的文件夹,里面建

  • 再建xxx的文件夹如(posts)将你命名的模块化函数名写xxx.ts文件
  • apiGetPosts部署到/post路由的数据函数
  • apiGetPostsDetail查询/post路由里数据的函数
  • PostSummary也是一个模块,提供一个数据输出的模板,后面讲,不急

apiGetPosts.ts

import { DataStore } from "../../data/data";
import {RequestHandler} from 'express';
import { PostSummary } from "../../model/share/postSummary";

export const apiGetPosts : RequestHandler = (req,res)=>{
res.json(DataStore.posts.map((item: any)=> new PostSummary(item)))
}

apiGetPostsDetail.ts

import { DataStore } from "../../data/data";
import {RequestHandler} from 'express';
import { PostSummary } from "../../model/share/postSummary";

export const apiGetPostsDetail : RequestHandler = (req,res)=>{
const selectedPost = DataStore.posts.find(
(element:any) => element.id == req.params.id
);
//检测数据,有返回,没有failed
if(selectedPost){
res.json(new PostSummary(selectedPost));
}else{
res.status(404).json({status:'failed',message:'posts not found'});
}
}

数据模板

在package.json同级下建

名为model的文件夹,里面建

  • 再建xxx的文件夹如(share)将你命名的模块化函数名写xxx.ts文件(PostSummary.ts)
  • 左边是json文件里的key,右边是类型
    export class PostSummary{
    userId: number;
    id: number;
    title: string;
    body: string;
    constructor(data:any){
    this.userId =data.userId
    this.id = data.id;
    this.title = data.title
    this.body = data.body;
    }
    }

实现查询时将添加的数据和另一个.json对应的id数据加上

原来基础上添加price,currency数据

//posts.json,内容是随便写的,按照key,value方式就可
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat ",
"body": "nnostrum rerum est autem sunt rem eveniet architecto",
"price" : 190,
"currency":"RMB"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "nqui aperiam non debitis possimus qui neque nisi nulla",
"price" : 1909,
"currency":"RMB"
}
]

另一个.json文件

  • /data/todos.json
    [
    {
    "postId": 1,
    "todoTitle": "delectus aut autem",
    "todoText": "delectus aut autem",
    "start": 4
    },
    {
    "postId": 2,
    "todoTitle": "delectus aut autem",
    "todoText": "delectus aut autem",
    "start": 5
    }
    ]

data.ts补充

import posts from './posts.json'
import todos from './todos.json'
export class DataStore{
static posts = posts;
static todos = todos;
}

添加数据模板

  • model/share/PostDetail.ts和model/share/todo.ts
  • todo.ts
    export class Todo{
    postId: number;
    start: number;
    todoTitle: string;
    todoText: string;
    constructor(data:any){
    this.postId =data.postId
    this.start = data.start;
    this.todoTitle = data.todoTitle
    this.todoText = data.todoText;
    }
    }
  • PostDetail.ts在原来的基础上添加,要引入PostSummary
    import { PostSummary } from "./postSummary";
    import { Todo } from "./todo";

    export class PostDetail extends PostSummary {
    price:number;
    currency:string;
    todos:Todo;
    constructor(postData:any,todoData:any){
    super(postData);
    this.price =postData.price;
    this.currency = postData.currency;
    this.todos = todoData.map((item:any)=> new Todo(item))
    }
    }

api方面

  • 由于我们在查询时补充,即只看apiGetPostsDetail文件
  • 替换掉原来的PostSummary
    import { DataStore } from "../../data/data";
    import {RequestHandler} from 'express';
    import { PostDetail } from "../../model/share/PostDetail";

    export const apiGetPostsDetail : RequestHandler = (req,res)=>{
    const selectedPost = DataStore.posts.find(
    (element:any) => element.id == req.params.id
    );
    if(selectedPost){
    const selectedTodos = DataStore.todos.filter(
    (item:any)=>item.postId == req.params.id
    );
    res.json(new PostDetail(selectedPost,selectedTodos));
    }else{
    res.status(404).json({status:'failed',message:'post not found'});
    }
    }

启动之后,用postman测试端口


以上是我的学习笔记~