如何使用快速服务器键入请求参数

How to Type a request parameter with express server

如何键入(打字稿)附加的 post 请求来修复错误?我想获取请求正文,但我无法正确输入。

谢谢!

import express = require('express');
import { Request } from 'express';
import bodyParser from 'body-parser';
import { parseBMI, calculateBMI } from './bmiCalculator';
import { calculateExercises } from './exerciseCalculator';

const app = express();
app.use(bodyParser.json());

app.get('/hello', (_,res) => {
  res.send("Good day");
});

app.get('/bmi', (req,res) => {
  const weight = Number(req.query.weight);
  const height = Number(req.query.height);
  console.log(weight,height);
  try {
    const {parseHeight, parseWeight} = parseBMI(height,weight);
    const out: string = calculateBMI(parseHeight,parseWeight);
    res.json({
      weight:parseWeight,
      height:parseHeight,
      bmi:out
    });
  } catch (e) {
    res.status(4004).json(e);
  }

});
app.post('/exercises',(req: Request<Array<number>,number>,res) => {
    const body:any = req.body;
    const dailyExercises = body.daily_exercises as Array<number>;
    const target = Number(body.target);

    res.json(calculateExercises(dailyExercises,target));
  });

const PORT = 3003;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

这仅涉及在 vscode

上使用 eslint 插件抛出错误的 /exercises 路由

您需要为您的请求定义一个接口:

interface Exercise {
    dailyExercises: number[],
    target: number
}

const exercise = req.body as Exercise

然后将你的 req.body 转换为 Exercise,你就有了一个严格输入的练习常数。