create a http server and parse authorization headers in typescript

To create an HTTP server that can parse authorization headers using TypeScript and Node.js, we can use the built-in http and url modules:

index.ts
import * as http from 'http';
import * as url from 'url';

const PORT = 3000;

const server = http.createServer(function (req, res) {
  const query = url.parse(req.url, true);
  const authHeader = req.headers.authorization;
  
  // Parse the authorization header if it exists
  if (authHeader) {
    const auth = authHeader.split(' ')[1];
    const credentials = Buffer.from(auth, 'base64').toString();
    const [username, password] = credentials.split(':');
    console.log(`Username: ${username}, Password: ${password}`);
  }
  
  // Send a response
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

server.listen(PORT, function () {
  console.log(`Server listening on http://localhost:${PORT}`);
});
760 chars
27 lines

In this code, we create an HTTP server listening on port 3000. When a request is received, we parse the URL and check for an Authorization header. If one exists, we parse the credentials and log them to the console. Finally, we send a response with a "Hello, World!" message.

Note that this is a very basic example, and in a real-world application you would likely want to do further validation and error handling when parsing the authorization header. Also, you should never store passwords in plain text – this example is simply for demonstration purposes.

gistlibby LogSnag