You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

curl发起PUT请求正常,fetch请求返回422错误的技术求助

解决Svelte中fetch PUT请求422错误问题

问题详情

构建Svelte应用时,调用API的PUT请求返回422 (Unprocessable Entity)错误,但终端用curl执行完全相同的请求却能正常获取token。甚至在API文档页面执行该请求也会返回422,只有curl能成功。

请求对比

正常工作的curl请求

curl -X 'PUT' 
'http://localhost:8000/auth/users/tokens' 
-H 'accept: application/json' 
-H 'Cookie: refreshToken=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

返回预期结果:

{
  "access_token": "string",
  "refresh_token": "string"
}

失败的Svelte fetch请求

const response = await fetch(`${SITE_DOMAIN}/auth/users/tokens`, {
  method: "PUT",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Cookie': `refreshToken=${refreshToken}`,
  },
});
console.log(response);

错误提示:

PUT http://localhost:8000/auth/users/tokens 422 (Unprocessable Entity)

补充截图:

  • API文档请求失败:API文档PUT请求返回422错误
  • curl请求成功:终端curl执行PUT请求成功

问题原因与修复方案

1. 缺失accept请求头

curl请求里明确携带了accept: application/json头,但你的fetch请求没有添加。部分API会要求客户端指定接受的响应格式,缺少这个头会导致服务器无法正确处理请求,返回422错误。

2. 多余的Content-Type设置

该PUT请求不需要发送请求体,curl也没有设置Content-Type,但你的fetch请求添加了'Content-Type': 'application/x-www-form-urlencoded',这会让服务器误以为你要提交表单数据,但实际没有请求体,触发校验失败。

修正后的fetch代码

const response = await fetch(`${SITE_DOMAIN}/auth/users/tokens`, {
  method: "PUT",
  headers: {
    'accept': 'application/json', // 补上必填的accept头
    'Cookie': `refreshToken=${refreshToken}`,
  },
  // 可选:如果refreshToken来自浏览器Cookie,用credentials自动携带,避免手动拼接出错
  credentials: 'include' 
});
console.log(response);

额外检查项

  • 确认refreshToken变量是否正确获取,没有空值或格式错误(比如特殊字符未转义)。
  • 如果使用credentials: 'include',需确保API的CORS配置允许携带凭证。

内容的提问来源于stack exchange,提问作者zemmsoares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:50:24