登录功能开发遇TypeError: JSON.stringfy is not a function错误求助
问题描述
点击登录页面的登录按钮时,通过JS获取用户名和密码输入框的值,向https://fakestoreapi.com/auth/login服务发送请求;收到服务响应后,从登录页跳转到仪表盘。但控制台报错:TypeError: JSON.stringfy is not a function,相关代码如下:
document.addEventListener("DOMContentLoaded", function() { loginform.addEventListener("submit", function(event) { event.preventDefault() const username = document.getElementById("username").value; const password = document.getElementById("password").value; const data = { username, password } console.log(JSON.stringfy(data)) fetch('https://fakestoreapi.com/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => console.log(json)) .catch(err => console.log(err.message)); }); });
解决方案
报错核心是拼写错误:你把JSON.stringify()写成了JSON.stringfy()(正确拼写是i在f之前)。
修复步骤
- 修正拼写错误:将
console.log(JSON.stringfy(data))改为console.log(JSON.stringify(data)) - 添加登录成功后的跳转逻辑:在第二个
.then()回调中加入页面跳转代码
完整修复代码
document.addEventListener("DOMContentLoaded", function() { // 确保获取到表单元素,替换为你的表单实际ID const loginform = document.getElementById("loginform"); loginform.addEventListener("submit", function(event) { event.preventDefault() const username = document.getElementById("username").value; const password = document.getElementById("password").value; const data = { username, password } console.log(JSON.stringify(data)) fetch('https://fakestoreapi.com/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(json => { console.log(json); // 替换为你的仪表盘实际URL window.location.href = "/dashboard"; }) .catch(err => console.log(err.message)); }); });
额外提示:如果之前没有显式获取loginform元素,必须先通过getElementById或其他方式获取,避免出现loginform is not defined的新错误。
内容的提问来源于stack exchange,提问作者E lal
相关产品推荐
相关产品推荐

