调用Reqres API登录接口返回400错误,提示缺少邮箱或用户名
报错根源与修复步骤
一、Postman请求报错原因
Reqres 的 /api/login 接口仅从请求体读取email、password参数,不识别URL拼接的query参数。你将参数放在URL中的写法,服务端无法获取对应字段,直接返回Missing email or username错误。
正确操作是将参数配置到Postman的x-www-form-urlencoded或JSON格式的请求体中,而非URL参数栏。
二、前端fetch代码报错原因
代码存在两处错误:
- 请求体格式不匹配:已设置
Content-Type: application/x-www-form-urlencoded,但body传入了包含myData属性的对象,fetch会将对象序列化为[object Object],服务端无法解析出有效参数。 - 多余的对象包裹:
myData已经是符合form-urlencoded格式的字符串,不需要额外包一层对象。
修复方案
直接传参数字符串写法
form.addEventListener("submit", function(e){ e.preventDefault(); const myData = 'email=eve.holt@reqres.in&password=cityslicka' fetch("https://reqres.in/api/login", { method: 'post', headers : {"Content-Type": "application/x-www-form-urlencoded"} , body: myData, }) .then(res => res.json()) .then(data => console.log("登录返回:", data)) })
更稳定的URLSearchParams写法
form.addEventListener("submit", function(e){ e.preventDefault(); // 自动处理参数编码,避免手动拼接特殊字符出错 const myData = new URLSearchParams({ email: 'eve.holt@reqres.in', password: 'cityslicka' }) fetch("https://reqres.in/api/login", { method: 'post', body: myData // 此时fetch会自动设置正确的Content-Type,无需手动声明headers }) .then(res => res.json()) .then(data => console.log("登录返回:", data)) })
注意:Reqres 该接口的测试账号有效,只要参数传递位置正确即可正常返回
token字段。
内容的提问来源于stack exchange,提问作者localhost
相关产品推荐
相关产品推荐

