反应本地不会在模拟器上本地获取

时间:2019-12-09 20:55:19

标签: node.js react-native

我在iOS和Android上遇到问题。我正在使用以下代码:

fetch('https://192.168.0.143:3000/auth/signin').then(() => console.log('ok')).catch(error => console.log(error));

这是简化的课程,但您会明白的。

这不起作用,出现“网络请求失败”错误。当我在邮递员中对其进行测试时,它可以工作! https://localhost:3000/auth/signin也适用于邮递员(192.168.0.143是我的本地IP),但不适用于react-native提取。

我已经创建了一个自签名密钥,我的节点js服务器代码如下:

https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
}, app).listen(3000,
() => console.log('listening...'))

server.key和server.cert都在app.js(nodejs)所在的文件夹中。服务器正在运行。

我的自签名证书是否有问题?或者我在哪里可以找到我的问题?

编辑

我已经创建了node.js脚本的新部分:

const test = (req, res) => {
    res.status(200).send('OK').end()
}
app.get('/test', test)

因此,当我在ios模拟器上的野生动物园中访问https://localhost:3000/test时,会看到“确定”。但是网络请求仍然在我的应用程序中始终失败。我认为这与我的自签名证书有关,但我不知道确切的问题。

1 个答案:

答案 0 :(得分:1)

您需要检查的第一件事是,从模拟器/物理设备上对本地服务器https://192.168.0.143:3000进行ping操作。您将从那里得到回应。

iOS 上,您可能需要在info.plist中添加以下内容

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

Android 上,如果您将react-native-pinch用于我的项目,则必须对文件HttpUtil.java使用HTTP协议。默认情况下,全部使用HTTPS协议。

此外,您可能希望将工作站的IP包含在android/app/main/res/xml/下的network_security_config.xml文件中。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="system"/>
            <certificates src="user"/>
        </trust-anchors>
    </base-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">YOUR IP ADDRESS</domain>
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">127.0.0.1</domain>
        <!-- Modify the to your local IP address to allow app deployment on Android Pie -->
    </domain-config>
</network-security-config>
相关问题