create a http server and parse cookies in typescript

To create a HTTP server in TypeScript, we can use the popular web framework, Express.js. Here is a sample code that creates a server and parses cookies using the cookie-parser middleware:

index.ts
import express from 'express';
import * as http from 'http';
import cookieParser from 'cookie-parser';

const app = express();
const server = http.createServer(app);

app.use(cookieParser());

app.get('/', (req, res) => {
  // Access cookie using req.cookies object
  const username = req.cookies.username;
  if (username) {
    res.send(`Welcome back, ${username}!`);
  } else {
    // Set cookie using res.cookie method
    res.cookie('username', 'johndoe');
    res.send('Cookie has been set!');
  }
});

server.listen(3000, () => {
  console.log('Server is listening on port 3000');
});
591 chars
25 lines

In the above code, we first import the necessary modules - express, http, and cookie-parser. We then create an instance of the express server and create a HTTP server using the http module.

We then use the cookie-parser middleware to parse cookies in the incoming request. This middleware adds a cookies property to the request object, which we can use to access cookies.

In the route handler for the / route, we check if a cookie named username is present. If it is present, we greet the user. If it is not present, we set the cookie using the res.cookie method and send a response indicating that the cookie has been set.

Finally, we start the server and listen for incoming requests on port 3000.

Note that in order to use this code, you will need to install the required dependencies - express, http, and cookie-parser - using npm.

gistlibby LogSnag