React-Native无法连接到Node.js服务器(网络请求因错误而失败)

时间:2018-12-11 05:10:23

标签: node.js react-native socket.io

我正在尝试使一个简单的React Native应用程序能够将数据发送到Node.js服务器。

尽管如此,我仍然收到“网络请求失败”错误...

这是我第一次尝试实施这种项目,所以我可能犯了一个愚蠢的错误,但是已经有2天了,我一直找不到

感谢您的帮助或建议!

这是我的应用代码:

import React from 'react'
import {Text, View, TextInput, Button, StyleSheet, ImageBackground, Image, TouchableOpacity} from 'react-native' //import des components natifs
import {StackNavigator } from 'react-navigation';

const io = require('socket.io-client');
let socket = io('https://localhost:8080');

class Connexion extends React.Component{
    constructor(props){
        super(props);
 }

validationConnexion(){
    fetch('https://localhost:8080', {
      method: 'POST',
      headers: {
        Accept: 'text/plain',
        },
    }).catch((error) => {             
        console.error(error);
        });
}

在后端:

const express = require('express');
const https = require('https')
const socketio = require('socket.io');

const app = express();
const server = https.Server(app, function(req, res) {
   res.writeHead(200, {"Content-Type": "text/plain"});
   res.end();})
const websocket = socketio(server);
server.listen(8080, () => console.log('listening on *:8080'));

// The event will be called when a client is connected.
websocket.on('connection', (socket) => {
     console.log('A client just joined on', socket.id);
});

1 个答案:

答案 0 :(得分:1)

尝试使用您的IP地址而不是localhost

例如:

https://localhost:8080https://192。*:8080

相关问题