我在使用 Node.js 表单时遇到问题。我提交了日期,但它们没有到达后端。我有以下续集错误:
“错误:WHERE 参数“deviceName”具有无效的“未定义”值”。
我希望你能帮助我。我不知道出了什么问题。
我的 html 文件中的表单
<form method="POST" action="/settings/success">
<label> What's the name? </label> <br>
<input type="text" id="deviceName" value="IoT Device"> </input>
<button class="btn btn-light" type="button" id="checkButton" onclick="proofText()">Check</button>
<br>
<br><br>
<label> Which sensors do you use? </label> <br>
<input type="checkbox" class="form-check-input" name="devicetemp">
<label for="includeUppercase">Temperature</label> <br>
<input type="checkbox" class="form-check-input" name="devicehumid">
<label for="includeNumbers">Humidity</label> <br>
<input type="checkbox" class="form-check-input" name="devicepres">
<label for="includeSymbols">Pressure</label> <br>
<input type="checkbox" class="form-check-input" name="devicemotion">
<label for="includeSymbols">Motion</label> <br>
<br><br>
<button type="submit" class="btn btn-success">Onboarding starten</button>
</form>
以及后端文件index.js:
const express = require('express');
const router = express.Router();
router.post('/settings/success', async (req, res) => {
const name = req.body.deviceName;
const temp = req.body.devicetemp === 'on';
const humid = req.body.devicehumid === 'on';
const pressure = req.body.devicepress === 'on';
const motion = req.body.devicemotion === 'on';
let addDevice = await db.iot.findOrCreate({
where: {
deviceName: name,
},
});
let findNew = await db.iot.findOne({
where: {
deviceName: name,
},
});
let addData = await db.data.findOrCreate({
where: {
id: findNew.id,
temperature: temp,
humidity: humid,
pressure: pressure,
motion: motion
},
});
res.render('success.ejs');
});
我的服务器.js
const indexRouter = require('./routes/index');
const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.set('layout', 'layouts/layout');
app.use(expressLayouts);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
要获取输入字段的值,您必须使用属性“name”,而不是“id”。
这是修改后的代码:
<form method="POST" action="/settings/success">
<label> What's the name? </label> <br>
<input type="text" name="deviceName" value="IoT Device"> </input>
<button class="btn btn-light" type="button" id="checkButton" onclick="proofText()">Check</button> // Leave this one as id because you don't use its value.
<br>
<br><br>
<label> Which sensors do you use? </label> <br>
<input type="checkbox" class="form-check-input" name="devicetemp">
<label for="includeUppercase">Temperature</label> <br>
<input type="checkbox" class="form-check-input" name="devicehumid">
<label for="includeNumbers">Humidity</label> <br>
<input type="checkbox" class="form-check-input" name="devicepres">
<label for="includeSymbols">Pressure</label> <br>
<input type="checkbox" class="form-check-input" name="devicemotion">
<label for="includeSymbols">Motion</label> <br>
<br><br>
<button type="submit" class="btn btn-success">Onboarding starten</button>
</form>