HTML 输入元素 returns EJS 中带电子的空格

HTML input element returns blank spaces in EJS with electron

我正在做一个项目,运行 遇到了这个问题。

我有一个简单的 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>

现在,我尝试使用 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));
});

有人知道如何解决这个问题吗?

您不应在选择 emailpassword 时获取它们的值,而是在点击侦听器中获取值。请看下面的代码:

第一个更改: 在选择元素时删除 .value

const email = document.getElementById("email");
const password = document.getElementById("password");

第二个变化:获取点击监听器中的值。

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));
});