使用fetch将html表单数据发送到api的问题

问题描述 投票:-1回答:1

我想让用户在html表单中输入电子邮件和密码,然后输入条目并使用fetch将其发送到API

我知道那个机构:“email = x.xxxx%40xxx.xxx.xx&password = xxxxxx”,已经可以使用,但我正在努力使它需要用户输入,并且任何电子邮件/密码都可以添加到注册表中

我为html表单得到了什么

<div id="registerForm">
        <script>
        <form
            onSubmit={(event) => {
                event.preventDefault();
                console.log(event.target.elements.emailRegistration.value)
                console.log(event.target.elements.pswRegistration.value)
            }
        >
        </script>
        <div class='container'>
            <label for="emailReg">Register:</label>
            <input type="text" name="emailReg" id="emailReg" value={emailReg} placeholder="Enter Email" onChange={(event) => {
                regEmail(event.target.value);
            }}
            />
            <label for="pswReg"></label>
            <input type="password" name="pswReg" id="pswReg" value={pswReg} placeholder="Enter Password" >
            <button type= "submit" id="regBtn">Submit</button>
        </div>
        </form>
    </div>

我尝试过的Javascript获取代码

const regButton = document.getElementById("regBtn");
regButton.addEventListener("click", () => {
  fetch("https://api/register", {
    method: "POST",
    body: JSON.stringify({email: form.emailReg.value, password: form.pswReg.value}),
    headers: {
      "Content-type": "application/x-www-form-urlencoded"
    }
  })
    .then(function(response) {
      if (response.ok) {
        return response.json();
      }
      throw new Error("Network response was not ok");
    })
    .then(function(result) {
      let appDiv = document.getElementById("logapp");
      appDiv.innerHTML = JSON.stringify(result);
      regButton.disabled = true;
    })
    .catch(function(error) {
      console.log(
        "There has been a problem with your fetch operation: ",
        error.message
      );
    });
});

我希望能够将电子邮件/用户名发布到api,然后我可以用另一种形式登录到api但是当时没有任何反应当我打开页面时,我得到Uncaught SyntaxError: Unexpected token < index.html?emailLogin=&pswLogin=:24 Uncaught SyntaxError: Unexpected identifier并且意外的令牌错误在形成

javascript html fetch-api
1个回答
-1
投票

更改

headers: {
  "Content-type": "application/x-www-form-urlencoded"
}

headers: {
  "Content-Type": "application/json"
}
© www.soinside.com 2019 - 2024. All rights reserved.