create a http server and parse authorization headers in javascript

Here's an example code snippet that creates an HTTP server in JavaScript (using Node.js) and parses the Authorization header:

index.tsx
const http = require('http');

const server = http.createServer((req, res) => {
  const authHeader = req.headers.authorization;
  if (authHeader) {
    const encodedCredentials = authHeader.split(' ')[1];
    const decodedCredentials = Buffer.from(encodedCredentials, 'base64').toString('utf-8');
    const [username, password] = decodedCredentials.split(':');
    console.log(`Received credentials - username: ${username}, password: ${password}`);
  }

  res.write('Server is running');
  res.end();
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});
611 chars
20 lines

In this code, we first use the http.createServer method to create an HTTP server. Inside the server callback function, we extract the Authorization header from the request headers using req.headers.authorization.

We then split the header value by space and take the second value, which is the base64-encoded username and password. We use the Buffer.from method to decode the base64 value and get the original username and password string.

Finally, we log the decoded credentials and send a response to the client.

Note that this is a basic example and you may need to add your own authentication logic to verify the credentials sent by the client in production.

gistlibby LogSnag