无法将 android React Native 应用程序连接到 localHost .NET api

tla*_*eca 1 .net localhost visual-studio react-native react-native-android

我有一个 React Native 应用程序,它只需要登录并随后使用返回的 access_token 获取数据。我试图通过连接到在 localHost:50968 上运行的本地托管 .NET api 来调试错误。这返回

    TypeError: Network request failed
Run Code Online (Sandbox Code Playgroud)

我已经在manifext.xml 中启用了互联网权限。大多数谷歌搜索一直在说我需要将 localHost:50968 更改为我的 IP 地址。这是迄今为止使用 '192.168.0.2:50968/token 最接近的,但以下是响应。

    { type: 'default',
status: 400,
ok: false,
statusText: undefined,
headers: { map: { 'content-length': [ '334'
        ],
connection: [ 'close'
        ],
date: [ 'Thu,
            10 Aug201703: 19: 14 GMT'
        ],
server: [ 'Microsoft-HTTPAPI/2.0'
        ],
'content-type': [ 'text/html; charset=us-ascii'
        ]
    }
}, url: 'http: //192.168.0.2:50968/token',
 _bodyInit: 
 '<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">\r\n
<HTML>

<HEAD>
    <TITLE>Bad Request</TITLE>\r\n
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>\r\n

<BODY>
    <h2>Bad Request - Invalid Hostname</h2>\r\n
    <hr>
    <p>HTTP Error 400. The request hostname is invalid.</p>\r\n
</BODY>

</HTML>\r\n', _bodyText: '
<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"> \r\n
<HTML>

<HEAD>
    <TITLE>Bad Request
    </TITLE>\r\n
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>\r\n

<BODY>
    <h2>Bad Request - Invalid Hostname</h2>\r\n
    <hr>
    <p>HTTP Error 400. The request hostname is invalid.</p>\r\n
</BODY>

</HTML>\r\n'}
Run Code Online (Sandbox Code Playgroud)

我在 Visual Studio 中有一个断点正在等待请求,但我一生都无法让它工作。我的提取代码如下。

我尝试将这些作为 URL_LOGIN 并且都不起作用。' http://localHost:50968/token '; ' http://192.168.0.2:50968/token ';

    fetch(URL_LOGIN, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            //application/x-www-form-urlencoded
        },
        body: data
    }).then((response) => {
        var jsonResponse = JSON.parse(response._bodyInit);
        try {
            AsyncStorage.setItem('token', jsonResponse.access_token);
            loginUserSuccess(dispatch, response)
        } catch (error) {
            console.log(`Error while saving to Async Storage ${error.message}`)
            loginUserFailed(dispatch, error)
        }
    }).catch(response => {
       loginUserFailed(dispatch, response)
    });
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激。

tla*_*eca 5

终于找到了这个。以防万一其他人有这个问题。

http://briannoyesblog.azurewebsites.net/2016/03/06/calling-localhost-web-apis-from-visual-studio-android-emulator/

我发现的最好方法实际上是使用它

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti

拯救了我的身后。

  • 如果您遇到此问题,请使用第二个链接,它可以挽救生命。工具被 Keyoti 称为 Conveyor。谢谢您的帮助! (2认同)