POST请求Axios转Fetch后无响应:Body转换是否有误?
Axios转Fetch POST请求后无法获取服务器响应的问题解决
以下是可正常运行的Axios POST请求代码:
import React, { useState } from "react"; import Axios from "axios"; const [data, setData] = useState({ number: "", password: "", code: "" }) function handle(e) { const newdata = { ...data }; newdata[e.target.id] = e.target.value; setData(newdata); } function submit(e) { e.preventDefault(); const url = 'EXAMPLE'; Axios.post(url, { number: data.number, password: data.password, code: data.code }).then((response) => { if (response.ok) { return response.json(); } throw new Error('Something went wrong.'); }) .then((responseJson) => { console.log(responseJson); }).catch((error) => { console.log(error + ", Or Please check your internet connection and try again."); }) }
将其转换为Fetch请求后,Network面板显示Payload与Axios一致,但无法获取服务器响应:
import React, { useState } from "react"; const [data, setData] = useState({ number: "", password: "", code: "" }) function handle(e) { const newdata = { ...data }; newdata[e.target.id] = e.target.value; setData(newdata); } function submit(e) { e.preventDefault(); const url = 'EXAMPLE'; fetch(url, { method: 'POST', body: JSON.stringify(data) }).then((response) => { if (response.ok) { return response.json(); } throw new Error('Something went wrong.'); }) .then((responseJson) => { console.log(responseJson); }).catch((error) => { console.log(error + ", Or Please check your internet connection and try again."); }) }
问题原因
Axios在发送JSON格式请求体时,会自动设置请求头Content-Type: application/json,但Fetch API不会默认添加这个请求头。即便用JSON.stringify()转换了请求体,服务器若未收到Content-Type标识,就无法正确解析JSON格式的请求体,自然无法返回预期响应。
解决方案
在Fetch请求的配置中添加headers,明确指定Content-Type为application/json:
function submit(e) { e.preventDefault(); const url = 'EXAMPLE'; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' // 新增请求头配置 }, body: JSON.stringify(data) }).then((response) => { if (response.ok) { return response.json(); } throw new Error('Something went wrong.'); }) .then((responseJson) => { console.log(responseJson); }).catch((error) => { console.log(error + ", Or Please check your internet connection and try again."); }) }
添加后服务器就能正确识别请求体格式,解析后返回正常响应。
内容的提问来源于stack exchange,提问作者Soheil.T
相关产品推荐
相关产品推荐

