![](/img/trans.png)
[英]Node.js - How can I check if a parsed json has the same structure of a class?
[英]How can I do a validation check with node.js and json?
我剛開始使用 web 開發,我知道它們是類似的問題,但不幸的是我找不到解決方案......
在我的 html 文件中,我有一個輸入字段,用戶應在其中輸入其 ID。 我想通過 json 文件(存儲 ID 的位置)檢查是否輸入了正確的 ID。 對我來說,我不清楚如何通過節點 js 進行驗證檢查。 有什么建議么?
測試.html
<form class="test">
<label class="ID-Field">
<input id="value" type="text" required/>
<span class="placeholder">Your ID</span>
</label>
</form>
數據.json
{
"inforamtion":[
{
"ID": "123",
"Name": "Vincent"
},
{
"ID": "452",
"Name": "Jean"
},
{
"ID": "678",
"Name": "Sopfie"
}
]
}
index.js
const http =require('http');
const express = require('express');
const { urlencoded } = require('body-parser');
const { fstat } = require('fs');
const { response } = require('express');
const app = express();
app.get('/test.html',function (req,res) {
res.sendFile(path.join(__dirname +'/test.html'));
})
app.listen(4000, console.log(`Server running at http://localhost:4000`));
//Check ID
app.post('/database.json', (req, res) => {
const result = information.find(({id}) => id === 'defined');
console.log(result)
})
您可以在您的節點應用程序中創建新端點,例如。
app.post('/check', (req, res) => {})
填寫表格后,您可以向此端點執行 ajax 請求,您將在其中發送用戶提供的 ID。 在該端點中,您可以獲得 json 文件,並嘗試查找您是否有任何 ID 由用戶提供的 object。
但首先您需要將數據 json 更改為數組才能使用。find function https://developer.mozilla.org/en-GlobalObjects/docs/web/findReference
[
{ id: 1, name: "Some name"},
{ id: 2, name: "Another name"}
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.