React Native Post Request via Fetch throws Network Request Failed

前端 未结 9 1495
[愿得一人]
[愿得一人] 2020-12-15 16:51

I´ve came across the following error. At the moment I developing an Android App with React Native therefore I´m planning to use fetch for doing a post request for me.

相关标签:
9条回答
  • 2020-12-15 17:19

    Developing with Windows OS/PHP built-in server/react-native Android on device:

    • check server local IP address (ipconfig), e.g. 172.16.0.10
    • in react-native fetch use this URL and proper port (fetch('http://172.16.0.10:8000/api/foo))
    • run PHP built-in server with this specific IP instead of the localhost: php -S 172.16.0.10:8000 ...
    • turn off Windows firewall for the private networks

    That fixed the connection problem between Android phone and the local server for me.

    0 讨论(0)
  • 2020-12-15 17:21

    I had a major issue doing the same on the android emulator. On iOS approving the domain in the info.plist was necessary. To be clear I was attempting to login to my .NET web hosted API.

    The fix was to make sure the post data was parameterised.( I'm pretty sure that's a word)

    export const loginUser = ({ userName, password }) => {
    const data = `UserName=${userName}&Password=${password}&grant_type=password`
        return (dispatch) => {
            dispatch({ type: LOGIN_USER })
    
            fetch(URL_LOGIN, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: data
                // body: {
    
                //     UserName: userName,
                //     Password: password,
                //     grant_type: 'password'
    
                // }
    
            })
                .then((response) => { 
                    loginUserSuccess(dispatch, response)
                })
                .catch((response) => {
                    loginUserFailed(dispatch, response)
                })
        };
    };
    
    0 讨论(0)
  • 2020-12-15 17:22

    step1> add android:usesCleartextTraffic="true" line in AndroidManifest.xml like:

    // add this line ... step2> Delete all debug folder from your android folder..

    0 讨论(0)
提交回复
热议问题