我正在嘗試通過 req.body 在以下 html 中獲取復選框“1”的值。但是,在 req.body 中,僅包括用戶名和密碼值(也不包括密碼確認)。
如何在 req.body 中包含 passwordConfirm 和 checkbox 的值?或者是否有另一種方法可以在沒有 req.body 的情況下獲取 checkbox 的值?
<form action="/register" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<label for="passwordConfirm">Confirm Password:</label>
<input type="password" id="passwordConfirm" name="passwordConfirm"><br><br>
<label>?</label>
<input type="checkbox" id="checkbox" name="checkbox" value="1"><br><br>
<button type="submit">Submit</button>
</form>
index.js
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post("/register", (req, res) =\> {
console.log(req.body.checkbox); //returns undefined
});
我嘗試將 <script> 放入 html 以包含一個函式,該函式回傳訪問檔案物件的復選框的值并在服務器端 js 檔案中呼叫該函式,但它不起作用(服務器端 js 無法在客戶端呼叫該函式-側js)。
uj5u.com熱心網友回復:
我嘗試了以下服務器端代碼,它可以作業。
app.use(express.urlencoded({ extended: false }));
app.post("/register", express.json(),(req, res) => {
console.log(req.body);
});
uj5u.com熱心網友回復:
<form method="POST" action="/">
<input type="text" name="username" placeholder="username">
<input type="submit">
</form>
uj5u.com熱心網友回復:
const express = require('express');
const app = express();
/** Decode Form URL Encoded data */
app.use(express.urlencoded());
/** Show page with a form */
app.get('/', (req, res, next) => {
res.send(`<form method="POST" action="/">
<input type="text" name="username" placeholder="username">
<input type="submit">
</form>`);
});
/** Process POST request */
app.post('/', function (req, res, next) {
res.send(JSON.stringify(req.body));
});
/** Run the app */
app.listen(3000);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449379.html
標籤:javascript html 节点.js 表示
