node.js - 使用 Node 创建服务器并使用 React Native 获取端点

标签 node.js json react-native

我有 json 文件并创建了 node.js 服务器来设置端点,然后通过我的 React Native 应用程序获取此数据。如果我没记错的话,它在周五工作正常,但我不得不搞砸一些东西,现在我完全不知道如何修复它。每次我都会收到错误:

Possible Unhandled Promise Rejection (id: 0): TypeError: Network request failed self.fetch/http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:27859:18 dispatchEvent@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:29144:13 setReadyState@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:28897:15 __didCompleteResponse@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:28724:11 send/<@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:28834:18 emit@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:4538:15 __callFunction@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:2608:22 callFunctionReturnFlushedQueue/<@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:2385:11 __guard@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:2561:13 callFunctionReturnFlushedQueue@blob:http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:2384:9 onmessage@http://192.168.1.39:8081/debugger-ui/debuggerWorker.js:72:25

我的 Node 服务器:

const filename = './logos.json';

const server = http.createServer((req, res) => {

        if (req.url === "/logo") {
            res.writeHead(200, { "Content-Type": "application/json" });
            fs.createReadStream(__dirname + "/logos.json").pipe(res)
        }
})
server.listen(3000, (err) => {
    if (err) throw err;
    console.log('server is listening on port 3000');
})

和我的 RN 代码:

syncLogoData = () => {
    fetch('http://localhost:3000/logo')
        .then(resp => resp.json())
        .then(data => console.log(data))
        .catch(err => console.log(err))
    }

最佳答案

您似乎正在尝试在设备上运行此程序。设备不知道 localhost 指向您的服务器。在您的 syncLogoData 中,将 uri 更改为 http://ip_address:3000/logo 它应该可以工作。

在计算机浏览器上打开http://localhost:3000/logo也有助于确保您的服务器代码正确。

关于node.js - 使用 Node 创建服务器并使用 React Native 获取端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55684572/

相关文章:

javascript - Angular ajax : Unexpected token I in JSON at position 0

ios - 如何读取本地 JSON 文件进行测试

react-native - 如何在 native react 中加密和解密文本?

javascript - REST API 测量服务器端响应时间(性能)。

javascript - 为什么我的异步函数返回得太快?

node.js - 如何将 http 模块与 bluebird 协程一起使用?

javascript - Ruby on Rails 生成 Json

javascript - 如何处理React Native中多个组件的数据获取?

css - 在不影响其 child 的情况下查看边框阴影

javascript - 使用 webpack-dev-server 启动时,Docker 容器未按预期发布端口