【问题标题】:create server with node and get endpoint with React Native使用节点创建服务器并使用 React Native 获取端点
【发布时间】:2019-04-15 07:44:56
【问题描述】:

我有 json 文件并创建了 node.js 服务器来设置端点,然后通过我的 React Native 应用程序获取这些数据。如果我没记错的话,它在星期五工作正常,但我不得不把事情搞砸,现在我完全不知道如何解决它。我总是得到错误:

可能的未处理的 Promise Rejection (id: 0): TypeError: Network 请求失败 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 发送/http://192.168.1.39:8081/1c49a23b-7fbb-c640-a946-c1e001192c92:28834:18 发射@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/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

我的节点服务器:

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

【问题讨论】:

  • 您的请求是端口3000 但错误日志显示8081 http://192.168.1.39:8081 再次检查
  • @naga-elixir-jar 8081 是 React Native 打包器运行的地方。

标签: node.js json react-native


【解决方案1】:

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

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

【讨论】:

  • 谢谢老兄,我已经解决了这个问题,但是和你刚才说的完全一样,所以我会把它标记为正确答案:)
猜你喜欢
  • 2021-09-08
  • 1970-01-01
  • 2018-05-05
  • 2023-04-05
  • 2021-07-22
  • 2018-09-08
  • 2022-08-09
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多