Search code examples
node.jstypescriptflutterubuntuovh

Why isn't my data being retrieved on my NodeJS Backend?


I'm currently working on a project which requires me to build a mobile application using flutter frontend and a NodeJS backend. I've purchased a VPS from OVHcloud which runs Ubuntu 20.04 and followed multiple tutorials to create a server for me to go off of. I wrote some very basic frontend and backend code merely just to test the connection and to make sure that the data is being sent to the server and the response is being sent back to me. I also have the OVHcloud VPS firewall disabled to prevent any issues although I plan on enabling it soon and for anyone wondering, the firewall rules that I've added are basically the same as the tutorial here except with a different SSH port.

Here is my flutter frontend code:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:nagahni/client.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MyProject',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'MyProject'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? _message;

  // This function will send the message to our backend.
  void sendMessage(msg) {
    WebSocketChannel? channel;
    try {
      channel = IOWebSocketChannel.connect('ws://I put my IP here:I put my port here');
      print('connected');
    } catch (e) {
      if (kDebugMode) {
        print(
            "Error: $e");
      }
    }
    channel?.sink.add(msg);

    channel?.stream.listen((event) {
      if (event != null) {
        if (kDebugMode) {
          print(event);
        }
      }
      channel!.sink.close();
    });
    if (kDebugMode) {
      print(msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: [
            Center(
              child: TextField(
                onChanged: (e) => _message = e,
              ),
            ),
            Center(
              child: TextButton(
                child: const Text("Send String"),
                onPressed: () {
                  // Check if the message isn't empty.
                  if (_message!.isNotEmpty) {
                    sendMessage(_message);
                  }
                },
              ),
            ),
            const SizedBox(height: 12),
            TextButton(
              onPressed: () {
                sendObject();
              },
              child: const Text('Send Object'),
            ),
          ],
        ),
      ),
    );
  }
}

Here is my Backend NodeJS code written in TypeScript:

import express from 'express';
import { Server } from 'ws';
const PORT = process.env.MAIN_PORT; // This is basically the SSH port + 1 ex. if 22, then this would be 23
require('dotenv').config()

const server = express()
        .use((req, res) => res.send("Hi there"))
        .listen(PORT, () => console.log(`Listening on Port ${PORT}`))

const wss = new Server({ server });

wss.on('connection', function(ws, req) {
    ws.on('message', message => {
        var data = message.toString();
        if(data === "Hello") {
            console.log(data);
            ws.send("Hi from TypeScript NodeJS");
        } else {
            console.log(data);
            ws.send("Say hello to me!");
        }
    })
})

Now my problem is that from the frontend of things, the terminal displays connected along with the string message we are sending. And in the backend, All is says is that it is listening to the port 23 for example but it does not print out any data or respond or do anything.

What I did notice is that when using tsc --w I get 147 errors from the express module for some reason but then it compiles the file normally and it says that it is listening to the port. What's even stranger is that if I run the same exact code on my PC, I won't get an error and everything will compile normally. But again it does not display any data on my end as it should neither does it return a response.

The error for the express module for anyone interested:

[5:51:56 PM] Starting compilation in watch mode...

node_modules/@types/express-serve-static-core/index.d.ts:104:68 - error TS1110: Type expected.

104 type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
                                                                       ~~~

node_modules/@types/express-serve-static-core/index.d.ts:104:77 - error TS1005: '}' expected.

104 type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
                                                                                ~

node_modules/@types/express-serve-static-core/index.d.ts:104:78 - error TS1128: Declaration or statement expected.

104 type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
                                                                                 ~

node_modules/@types/express-serve-static-core/index.d.ts:104:80 - error TS1005: ';' expected.

104 type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
                                                                                   ~

node_modules/@types/express-serve-static-core/index.d.ts:106:33 - error TS1005: ';' expected.

106     RemoveTail<RemoveTail<S, `/${string}`>, `-${string}`>,
                                    ~

node_modules/@types/express-serve-static-core/index.d.ts:106:48 - error TS1005: ';' expected.

106     RemoveTail<RemoveTail<S, `/${string}`>, `-${string}`>,
                                                   ~

node_modules/@types/express-serve-static-core/index.d.ts:107:8 - error TS1005: ';' expected.

107     `.${string}`
           ~

node_modules/@types/express-serve-static-core/index.d.ts:113:22 - error TS1005: ';' expected.

113     : Route extends `${string}(${string}`
                         ~

node_modules/@types/express-serve-static-core/index.d.ts:113:23 - error TS1005: ';' expected.

113     : Route extends `${string}(${string}`
                          ~

node_modules/@types/express-serve-static-core/index.d.ts:113:33 - error TS1005: ')' expected.

113     : Route extends `${string}(${string}`
                                    ~

node_modules/@types/express-serve-static-core/index.d.ts:115:26 - error TS1005: ';' expected.

115         : Route extends `${string}:${infer Rest}`
                             ~

node_modules/@types/express-serve-static-core/index.d.ts:115:27 - error TS1005: ';' expected.

115         : Route extends `${string}:${infer Rest}`
                              ~

node_modules/@types/express-serve-static-core/index.d.ts:115:35 - error TS1128: Declaration or statement expected.

115         : Route extends `${string}:${infer Rest}`
                                      ~

node_modules/@types/express-serve-static-core/index.d.ts:115:37 - error TS1005: ';' expected.

115         : Route extends `${string}:${infer Rest}`
                                        ~

node_modules/@types/express-serve-static-core/index.d.ts:115:44 - error TS1005: ';' expected.

115         : Route extends `${string}:${infer Rest}`
                                               ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:119:52 - error TS1005: ';' expected.

119                 : GetRouteParameter<Rest> extends `${infer ParamName}?`
                                                       ~

node_modules/@types/express-serve-static-core/index.d.ts:119:53 - error TS1005: ';' expected.

119                 : GetRouteParameter<Rest> extends `${infer ParamName}?`
                                                        ~

node_modules/@types/express-serve-static-core/index.d.ts:119:60 - error TS1005: ';' expected.

119                 : GetRouteParameter<Rest> extends `${infer ParamName}?`
                                                               ~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:119:70 - error TS1128: Declaration or statement expected.

119                 : GetRouteParameter<Rest> extends `${infer ParamName}?`
                                                                         ~

node_modules/@types/express-serve-static-core/index.d.ts:123:28 - error TS1005: ';' expected.

123             (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
                               ~

node_modules/@types/express-serve-static-core/index.d.ts:123:29 - error TS1005: ';' expected.

123             (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
                                ~

node_modules/@types/express-serve-static-core/index.d.ts:123:53 - error TS1005: '(' expected.

123             (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
                                                        ~

node_modules/@types/express-serve-static-core/index.d.ts:123:55 - error TS1005: ';' expected.

123             (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
                                                          ~

node_modules/@types/express-serve-static-core/index.d.ts:123:62 - error TS1005: ';' expected.

123             (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
                                                                 ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:239:41 - error TS1005: ';' expected.

239      * Map the given param placeholder `name`(s) to the given callback(s).
                                            ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:248:31 - error TS1005: ';' expected.

248      * of the user. Once the `next()` function is invoked, just like middleware
                                  ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:274:62 - error TS1005: ';' expected.

274      * Special-cased "all" method, applying the given route `path`,
                                                                 ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:372:49 - error TS1005: ';' expected.

372  * @param P  For most requests, this should be `ParamsDictionary`, but if you're
                                                    ~~~~~~~~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:373:59 - error TS1005: ';' expected.

373  * using this in a route handler for a route that uses a `RegExp` or a wildcard
                                                              ~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:374:5 - error TS1005: ';' expected.

374  * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
        ~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:374:25 - error TS1005: ';' expected.

374  * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
                            ~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:374:44 - error TS1005: ';' expected.

374  * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
                                               ~~~

node_modules/@types/express-serve-static-core/index.d.ts:375:31 - error TS1005: ';' expected.

375  * which case you should use `ParamsArray` instead.
                                  ~~~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:380:84 - error TS1005: ';' expected.

380  *     app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary`
                                                                                       ~~~~~~~~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:395:13 - error TS1005: ';' expected.

395      * The `Referrer` header field is special-cased,
                ~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:396:14 - error TS1005: ';' expected.

396      * both `Referrer` and `Referer` are interchangeable.
                 ~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:396:29 - error TS1005: ';' expected.

396      * both `Referrer` and `Referer` are interchangeable.
                                ~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:409:20 - error TS1005: ';' expected.

409      * Aliased as `req.header()`.
                       ~~~

node_modules/@types/express-serve-static-core/index.d.ts:418:28 - error TS1005: ';' expected.

418      * Check if the given `type(s)` is acceptable, returning
                               ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:419:45 - error TS1005: ';' expected.

419      * the best match when true, otherwise `undefined`, in which
                                                ~~~~~~~~~

node_modules/@types/express-serve-static-core/index.d.ts:422:13 - error TS1005: ';' expected.

422      * The `type` value may be a single mime type string
                ~~~~

node_modules/@types/express-serve-static-core/index.d.ts:496:56 - error TS1005: ';' expected.

496      * Parse Range header field, capping to the given `size`.
                                                           ~~~~

... wayy more errors but i cannot paste it all ... 

[5:53:55 PM] Found 147 errors. Watching for file changes.

The steps I took for these errors to appear are as follows:

  1. mkdir node_project
  2. cd node_project
  3. npm init -y
  4. npm i @types/express
  5. npm i express
  6. npm i @types/ws
  7. npm i ws

Can anyone help me understand why the data isn't being sent/received?


Solution

  • Did you try checking if https port is open on the vps . Try checking the API call with https