DEV Community

Jen C.
Jen C.

Posted on

WebSocket with Node.js and React using TypeScript (1) - Set up HTTP server and check the server running status

full codes

Read the port number from the environment variable file

Use dotenv

import dotenv from 'dotenv';

dotenv.config();
const port = process.env.PORT;`
Enter fullscreen mode Exit fullscreen mode

Create a HTTP server and listen to the given port

...

import * as http from 'http';

...

const server = http.createServer();
server.listen(port, () => {
    console.log('Server started');
});
Enter fullscreen mode Exit fullscreen mode

Check the server running status

Pass a function (request, response) => { // do something } into createServer as the request handler. When the http server receives a HTTP request, the request handler will handle it.

For example, set the response header (status code 200 and the response type), send a text as a response to the client, and then end the response object (which is a WritableStream):

...

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello!\n');
});

...
Enter fullscreen mode Exit fullscreen mode

Open a browser to test

Server is running on localhost

Reference

  1. https://blog.logrocket.com/websocket-tutorial-real-time-node-react/#use-websockets-node-js-react
  2. https://dhruv-saksena.medium.com/websocket-development-with-typescript-from-scratch-782436d3e3be
  3. https://stackabuse.com/how-to-start-a-node-server-examples-with-the-most-popular-frameworks/
  4. https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction

Top comments (0)