我試圖用是的來驗證我的快速端點中的資料。看了幾個教程后,我遇到了以下錯誤。
如果我嘗試在我的中間件中驗證我的資料,它總是會回傳一個錯誤。登錄 req.body 后,我注意到它是undefined。
這是我的以下方法(都在不同的檔案中)。我的架構如下所示:
const loginSchema = yup.object({
body: yup.object({
email: yup.string().email().required(),
password: yup.string().min(3).max(16).required()
})
})
module.exports = loginSchema;
我的驗證中間件函式如下所示:
const validation = (schema) => async (req, res, next) => {
console.log(JSON.stringify(req.body)) // is undefined
try {
await schema.validate({
body: req.body
});
return next();
} catch(err) {
res.status(400).json({err})
}
};
module.exports = validation;
我在express.js 后端的端點如下所示:
// validation and schemas has been imported
router.post("/login", validation(schemas), (req, res) => {
// some code
})
如果我在發送 post 請求后嘗試驗證我的資料,它總是回傳以下內容:
{
"err": {
"value": {
"body": {}
},
"path": "body.password",
"type": "required",
"errors": [
"body.password is a required field"
],
"params": {
"path": "body.password"
},
"inner": [],
"name": "ValidationError",
"message": "body.password is a required field"
}
}
有沒有人有同樣的問題?因為我沒有發現任何關于這種錯誤的資訊。我使用了這種模式:https ://dev.to/franciscomendes10866/schema-validation-with-yup-and-express-js-3l19
uj5u.com熱心網友回復:
您需要使用 body-parser 包來讀取“req.body”。
安裝包并在 server.js 檔案中使用它。
npm 安裝正文決議器
import bodyParser from "body-parser";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/507567.html
標籤:javascript 节点.js 表示 对
