为什么React Native HTTP POST不起作用



export const login = () => {
return async (dispatch) => {
try {
const response = await fetch(
`https://simplyrem.com/srwl/haib/index.php`,
{
method: 'POST',
headers: {
accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
auth: 'XCXCXCXCX',
usernamex: 'XXXXX',
passwordx: 'XXXXXXXX',
}),
}
)
if (!response.ok) {
const errorResData = await response.json()
console.log(errorResData)
throw new Error('Something went wrong!')
}
const responseData = await response.json()
const userInfo = responseData
console.log(userInfo)
dispatch({
type: LOGIN,
userInfo: userInfo,
})
} catch (err) {
throw err
}
}
}

大家好,

我在输入凭证时使用了失眠测试了这个API,我得到了JSON响应,所以我知道API有效,我的凭证是正确的。我是React Native的新手,我不知道我是否通过使用body正确添加了参数:JSON.stringfy…显然,我已经用";X〃;在swift中,我也能得到响应,但当我试图在react-native中重新创建API调用时,我会得到错误

> [Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected EOF]
> * [native code]:null in parse
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:37:13 in tryCallOne
> - node_modules/react-native/node_modules/promise/setimmediate/core.js:123:24 in setImmediate$argument_0
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:130:14 in _callTimer
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:181:14 in _callImmediatesPass
> - node_modules/react-native/Libraries/Core/Timers/JSTimers.js:441:30 in callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:387:6 in __callImmediates
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:135:6 in  __guard$argument_0
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
> - node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:134:4 in flushedQueue
> * [native code]:null in flushedQueue
> * [native code]:null in invokeCallbackAndReturnFlushedQueue >

JSON Parse error: Unexpected EOF它通常是

尝试将不可覆盖的响应转换为json(如Html响应(转换为json时出错

为了安全起见,我通常首先使用.then(res => res.text()),然后使用console.log()alert()将其转换为字符串,以证明响应是否可转换为json,而不显示react本机的红框消息

如果响应是有效的json,您可以使用JSON.parse(responseText)自行转换

例如

fetch( "https://simplyrem.com/srwl/haib/index.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
Email: 'XXXXX',
password: "xxxxx",
}),
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.IsSuccess) {
console.log(responseJson);
alert(responseJson)
} else {
console.log(responseJson.ErrorMessage);
alert(responseJson.ErrorMessage)
}
})
.catch((error) => {
alert(error);
});

最新更新