如何鍵入(打字稿)附加的帖子請求以修復錯誤?我想獲取請求正文,但無法正確輸入。
謝謝!

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}`);
});
這僅涉及 /exercises 路由,該路由在 vscode 上使用 eslint 插件引發錯誤
uj5u.com熱心網友回復:
您將需要為您的請求定義一個介面:
interface Exercise {
dailyExercises: number[],
target: number
}
const exercise = req.body as Exercise
然后將你的型別req.body轉換為Exercise,你就有了一個嚴格輸入的練習常量。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/406803.html
標籤:
