我在做一个项目,遇到了这个问题。
我有一个简单的EJSE电子项目,正在加载主文件,就像这样。
mainWindow.loadURL("file://" + __dirname + "/public/app/index.ejs");
我的index.ejs文件也很简单。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./assets/style.css" />
</head>
<body>
<%- include ("./frame") %> <%- include ("./login") %>
<script src="assets/scripts/buttonSscripts.js"></script>
<script src="./assets/scripts/login.js"></script>
</body>
</html>
现在,im试图使用fetch发送API请求,但它总是说密码和用户名为空,而当我尝试console.log()
它们的值时,我只得到空格。输入元素中没有任何文本。
我的login.ejs文件:
<div class="login-container">
<div class="login-form">
<div class="img-wrapper" style="text-align: center">
<img
src="./assets/asd.png"
alt=""
height="220"
width="180
"
/>
<h1>Login in</h1>
</div>
<form>
<input type="text" id="email" name="email" />
<input type="text" id="password" name="password" />
<button type="button" id="submitbtn">Submit</button>
</form>
<script src="./assets/scripts/login.js"></script>
</div>
</div>
我的login.js文件:
const $ = require("jquery");
const loginbtn = document.getElementById("submitbtn");
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
loginbtn.addEventListener("click", (e) => {
console.log(email);
fetch("http://localhost:8080/api/v1/auth/login/email", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then((response) => response.json())
.then((responseJson) => console.log(responseJson));
});
谁有办法解决这个问题?
在选择email
和password
时,您不应该获取它们的值,而应该获取click侦听器中的值。请参阅下面的代码:
第一个更改:在选择元素时删除.value
。
const email = document.getElementById("email");
const password = document.getElementById("password");
第二个变化:获取click侦听器内部的值。
body: JSON.stringify({
email: email.value,
password: password.value,
})
完整代码如下:
const $ = require("jquery");
const loginbtn = document.getElementById("submitbtn");
const email = document.getElementById("email");
const password = document.getElementById("password");
loginbtn.addEventListener("click", (e) => {
console.log(email);
fetch("http://localhost:8080/api/v1/auth/login/email", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email.value,
password: password.value,
}),
})
.then((response) => response.json())
.then((responseJson) => console.log(responseJson));
});