Postman请求正常,React调用Github Gists API报404错误求助
问题分析与解决
你的核心问题是Axios PUT 请求的参数顺序错误,导致请求格式不符合 Github API 的要求。
错误原因
Axios 的 put 方法签名为:axios.put(url[, data[, config]]),而你当前代码把请求配置(config)放在了第二个参数位置(本该是请求体 data 的位置),第三个参数又传入了无关的 {noteId: noteId}。这会让 Axios 错误地把包含请求头的 config 当成请求体发送,导致 Github API 无法识别请求,直接触发错误。
另外,你手动设置的 Content-Length: "0" 属于多余配置,Axios 会根据请求体自动处理这个请求头。
修正后的请求代码
const starNote = async (noteId, token) => { const config = { headers: { Authorization: `Bearer ${token}`, // 移除不必要的 Content-Length 配置 }, }; try { // PUT 请求无需请求体,第二个参数传 null/空对象,将 config 放在第三个参数位置 const response = await axios.put(`${API_URL}/${noteId}/star`, null, config); console.log("request sent"); if (response.status === 204) { console.log("working", response); return true; } } catch (error) { // 完善错误日志,打印所有类型的错误信息,不止404 console.error("Star Gist 失败:", error.response?.data || error.message); // 抛出错误让 redux-thunk 捕获处理 throw error; } };
额外优化点
- 在切片函数的错误处理中,确保请求函数出错时抛出错误(如上修正代码中的
throw error),这样 redux-thunk 才能进入catch分支处理错误信息。 - 确认
API_URL是正确的 Github Gists API 域名(https://api.github.com/gists),避免 URL 拼接错误。
内容的提问来源于stack exchange,提问作者Umair
相关产品推荐
相关产品推荐

