【发布时间】:2020-08-03 11:54:45
【问题描述】:
我有一个 HTML 表单如下:
<form id="loginForm" name="loginForm">
<div class="form-group">
<input type="username" class="form-control" id="username" name="username" placeholder="Your username..." >
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="Your password...">
</div>
<button class="btn btn-primary btn-block btn-round" id="loginButton" type="submit">Login</button>
</form>
和一个包含以下代码的 Javascript 文件以发出 AJAX 请求:
//credits to @lndgalante
if (typeof window !== 'undefined') {
window.addEventListener('load', () => {
const form = document.getElementById('loginForm');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const elements = event.target;
const username = elements.username.value;
const password = elements.password.value;
const dataToSend = { username, password };
try {
console.log(JSON.stringify(dataToSend)); //To check variables are being passed correctly
return await fetch('/login', {
method: 'POST',
body: JSON.stringify(dataToSend),
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.log(error);
}
});
});
};
和一个带有相应 POST 路由的 node.js 文件:
app.post('/login', async (req, res) => {
try {
const username = req.body.username;
const password = req.body.password;
console.log(username, password, req.body); //To check variables are being passed correctly
...
}
});
但问题是,
console.log(JSON.stringify(dataToSend)); 按预期返回 {"username":"username1","password":"password1"} //or whatever the user input is,而
console.log(username, password, req.body) 返回undefined undefined {}。
有谁知道我做错了什么?
编辑:我正在使用 const app = express();,并且我的 node.js 文件中有 app.use(bodyParser.urlencoded({ extended: true }));。
【问题讨论】:
-
服务器端 JSON 解析器在哪里?
标签: javascript html node.js ajax post