使用fetch发起POST请求遇400及语法错误,问题已解决
问题重现
调用登录API时持续触发以下错误:
POST net::ERR_ABORTED 400 (Bad Request)
SyntaxError: Unexpected end of input
原请求配置代码:
const requestOptions = { method: 'POST', mode: 'no-cors', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: email, password: password }) };
原fetch请求代码:
await fetch("https://dev.rapptrlabs.com/Tests/scripts/user-login.php", requestOptions) .then(async response => await response.text()) .then(response => response === "" ? {} : JSON.parse(response) ) .catch(e => { console.log(e) })
API文档说明:
a. 表单验证通过后调用登录API
i. 使用POST请求
ii. Body传入email和password两个参数
iii. 测试账号:test@rapptrlabs.com / Test123
iv. 成功响应示例:
{ "user_id": 16,
"user_email": "test@rapptrlabs.com",
"user_username": "testuser",
"user_is_active": 1,
"user_profile_image": "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png",
"user_last_active_epoch": 1544680026,
"user_creation_epoch": 1544713200,
"user_is_new": 1,
"user_token": "6dd4737a8b7ec61313ae5e900420d46815e1d13b2902be71b97a8fbf1f421a3e" }
问题原因及解决方法
问题核心在于请求体格式不匹配:该API不接受JSON格式的请求体,需要使用FormData传递参数,同时调整请求配置。
修改后的请求代码示例:
// 构建FormData参数 const formData = new FormData(); formData.append('email', email); formData.append('password', password); const requestOptions = { method: 'POST', // 移除no-cors模式,否则无法正常解析响应内容 body: formData // 无需手动设置Content-Type,浏览器会自动添加适配FormData的请求头 }; await fetch("https://dev.rapptrlabs.com/Tests/scripts/user-login.php", requestOptions) .then(async response => { if (!response.ok) { throw new Error(`请求失败,状态码: ${response.status}`); } return response.json(); }) .then(response => { console.log('登录成功:', response); }) .catch(e => { console.log('登录失败:', e); })
关键修改点:
- 替换请求体格式:用
FormData替代JSON.stringify,匹配API的参数接收要求 - 移除
mode: 'no-cors':该模式会限制浏览器处理响应的能力,是触发SyntaxError的主要原因之一 - 省略手动设置
Content-Type:浏览器会自动为FormData添加正确的请求头,避免格式不匹配问题
内容的提问来源于stack exchange,提问作者antsmasher

