haibert
haibert

Reputation: 111

why is React Native HTTP POST not working?


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
        }
    }
}

Hello all,

I have tested this API using insomnia while inputting my credentials and I got a JSON response back, so I know that the API works and my credentials are correct. I am new to React Native and I don't know if I'm adding the parameters correctly by using body: JSON.stringify... Obviously, I've replaced the information with "X"s. In swift, I was able to also get a response back, but when I'm trying to recreate the API call in react-native I get error

> [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 >

Upvotes: 1

Views: 691

Answers (1)

Muhammad Idrees
Muhammad Idrees

Reputation: 198

JSON Parse error: Unexpected EOF it's usually

an error when you are trying to convert the non-covertable response to json (like Html response) into json

for safety I usually convert it first to string using .then(res => res.text()) then console.log() or alert() it to prove the response is Convertable to json or not without showing the react-native's red-box message,

if the response is valid json you can convert it by yourself with JSON.parse(responseText)

example like

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);
      });

Upvotes: 2

Related Questions