我正在嘗試使用 Express Validator 來驗證服務器端的異步 POST 查詢。PERN 堆疊。Express Validator 似乎不驗證任何內容,因為無論輸入如何,它總是回傳相同的回應。這是我的代碼。我不知道為什么這不起作用。請幫忙。
const { validationResult, check } = require('express-validator');
const myValidationResult = validationResult.withDefaults({
formatter: error => {
return {
myLocation: error.location,
};
},
});
app.post("/pathToContactTable",
[
check('req.body.aName')
.not().isEmpty() // checks appear to do nothing. violating them does nothing.
],
async (req, res, next) => {
console.log(req.body.aName); // prints out exactly what it should
var err = myValidationResult(req);
console.log(!err.isEmpty());
if (!err.isEmpty()) {
console.log(err.mapped())
return res.status(400).json({errors: err.array() });
} else {
try {
const { aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle } = req.body;
const newApplicant = await pool.query(`INSERT INTO applicantContactTable
( applicantName, applicantLastName, applicantPhone, applicantEmail, jobTitle1, jobDesc1, jobTitle2, jobDesc2, jobTitle3, jobDesc3, educationTitle, educationYear, certificationTitle)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING *`,
[aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle]
);
res.json(newApplicant.rows[0]);
} catch (err) {
console.error(err.message);
}
}
});
我預計驗證結果會有所不同,具體取決于通過前端表單輸入或不輸入值到 req.body.aName -->
const [aName, setAName] = useState("John");
const onSubmitForm = async (e) => {
e.preventDefault();
//ERROR CHECKS with error messages on screen prior to POST sending
//name first
var firstName = document.getElementById('firstNameInput').value;
if (validateName(firstName)) {
document.getElementById('firstName_error').classList.add('hidden');
} else if (!validateName(firstName)){
document.getElementById('firstName_error').classList.remove('hidden');
}
try { const body = { aName, aLastName, aPhone, aEmail, job1, jobDesc1, job2, jobDesc2, job3, jobDesc3, edu, eduYear, certTitle }; const response = await fetch("http://localhost:5000/pathToContactTable", method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
getApplicants();
// window.location = "/"; <-- This WAS inelegant and was replaced with a call to getApplicants();
} catch (err) {
console.log('this line fires in catch block of client POST')
console.error(err.message);
}
};
uj5u.com熱心網友回復:
您應該只將欄位名稱傳遞給check():
check('aName')
它將針對不同的請求物件驗證該欄位(如手冊中所述)。
如果您只想將檢查限制為req.body.aName,請使用:
body('aName')
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/534593.html
上一篇:insertId顯示為未定義
下一篇:如何為此撰寫測驗用例?
