我的班级模型:
class User {
userName: string;
password: string;
}
我的函数句柄:
const users = [];
function addUser(user: User) {
users.push(user);
}
快速路由器:
router.post('/users', (req, res) => {
addUser(req.body);
})
我想请求以下userModel格式。 但是,当我请求一个不遵循userModel格式的对象时,addUser函数仍然起作用,并将错误的对象格式推送给users []。
如果req.body与userModel不匹配,如何抛出错误
答案 0 :(得分:0)
我能够使用type-safe-json-decoder来实现所需的行为:
index.js
import express = require("express");
import bodyParser from "body-parser";
import { Decoder, object, string } from 'type-safe-json-decoder'
const app: express.Application = express();
app.use(bodyParser.json());
class User {
constructor(userName: string, password: string) {
this.userName = userName;
this.password = password
}
userName: string;
password: string;
}
const usersDecoder: Decoder<User> = object(
['userName', string()],
['password', string()],
(userName, password) => ({ userName, password })
);
const users: User[] = [];
function addUser(user: User) {
users.push(user);
console.log(users);
}
app.post('/add', (req, res) => {
const user: User = usersDecoder.decodeJSON(JSON.stringify(req.body))
addUser(user);
res.send("User added!");
});
app.listen(8080, () => console.log("Listening on 8080"));
package.json
{
"name": "ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"tsc": "tsc"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/express": "^4.16.1",
"body-parser": "^1.18.3",
"express": "^4.16.4",
"type-safe-json-decoder": "^0.2.0",
"typescript": "^3.4.1"
},
"devDependencies": {
"@types/body-parser": "^1.17.0"
}
}
要运行:
npm install
npm run tsc -- --init
npm run tsc
node index.js
使用正确的JSON执行POST时,您应该收到:User added!
。