我想让用户以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
并且意外的令牌错误在表格上
答案 0 :(得分:-1)
更改
headers: {
"Content-type": "application/x-www-form-urlencoded"
}
到
headers: {
"Content-Type": "application/json"
}