React前端注册用户时token未定义问题排查求助
问题分析与解决方案
关于api-token-auth/的405错误
这个错误和你注册时拿不到token的问题无关。api-token-auth/是认证登录接口,这类接口通常只支持POST请求(用来提交用户名密码换取token),用GET访问本身就不符合接口设计,报405是正常现象。
注册时token未定义的核心问题
从你的代码和描述来看,主要有以下几个关键点需要修复:
1. 表单输入ID与State字段不匹配
你的State里定义了charity_name、charity_abn,但对应的input标签ID是charity name、charity abn(带空格),导致handleChange无法正确给State赋值,提交给后端的参数会缺失这两个字段。后端可能因为参数不全,没有返回token(或者直接返回了错误)。
修复代码:
把input的ID改成和State字段完全一致:
<div className="charity_name"> <label htmlFor="charity_name">Charity Name</label> <input type="text" onChange={handleChange} id="charity_name" placeholder="Charity Name"/> </div> <div className="charity_abn"> <label htmlFor="charity_abn">Charity ABN</label> <input type="number" onChange={handleChange} id="charity_abn" placeholder="Charity ABN"/> </div>
另外,State里的about字段没有对应的输入框,要么添加输入框,要么从State里移除这个字段。
2. 缺少接口错误处理与返回内容排查
你现在直接假设接口会返回token,但没有检查请求是否成功,也没打印返回的具体内容。很多后端的注册接口本身不会返回token,需要注册成功后单独调用登录接口获取。
添加调试与错误处理:
修改postData函数,查看后端实际返回的数据:
const postData = async () => { const response = await fetch( `${import.meta.env.VITE_API_URL}users/`, { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify(register), } ); // 检查请求是否成功 if (!response.ok) { const errorInfo = await response.json(); console.error("注册请求失败:", errorInfo); throw new Error("注册失败,请检查输入"); } const responseData = await response.json(); console.log("后端返回数据:", responseData); // 打印看看有没有token return responseData; }
3. 注册后需单独调用登录接口获取token(如果后端要求)
如果调试后发现注册接口确实不返回token,那你需要在注册成功后,调用api-token-auth/接口(POST方法)来获取token:
const handleSubmit = (event) => { event.preventDefault(); if (register.username && register.password) { postData() .then(() => { // 注册成功后调用登录接口 return fetch(`${import.meta.env.VITE_API_URL}api-token-auth/`, { method: "post", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username: register.username, password: register.password }) }); }) .then(loginRes => loginRes.json()) .then(loginData => { if (loginData.token) { window.localStorage.setItem("token", loginData.token); navigate("/"); } else { console.error("登录接口未返回token:", loginData); } }) .catch(err => console.error(err)); } }
内容的提问来源于stack exchange,提问作者user20527388
相关产品推荐
相关产品推荐

