create a http server and parse cookies and return a json response in typescript

To create an HTTP server and parse cookies and return a JSON response in TypeScript, you can use the built-in http and url modules of node.js along with the cookie-parser middleware.

Here is an example code that demonstrates how to do this:

index.ts
import * as http from "http";
import * as url from "url";
import * as cookieParser from "cookie-parser";

const server = http.createServer((req, res) => {
  // parse cookies from the request headers using cookie-parser middleware
  const cookies = cookieParser.JSONCookies(req.headers.cookie || "");
  
  // handle the request
  if (req.url === "/api/myendpoint") {
    // return a JSON response
    const data = { message: "Hello World" };
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  } else {
    // handle 404 error
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 Page not found");
  }
});

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

In this code, we created an HTTP server using the createServer method of the http module. We then used the cookie-parser middleware to parse cookies from the request headers.

We handled the request by checking the URL of the request. If it matches our desired endpoint, we returned a JSON response with a message saying "Hello World". If the URL does not match, we sent a 404 error response.

We set the Content-Type to application/json to indicate that we are returning JSON data. We used the writeHead method to set the response status code and headers, and the end method to write the response body.

Finally, we listened for incoming requests on port 3000 using the listen method of the http server.

Note: don't forget to run npm install cookie-parser to install the dependency.

gistlibby LogSnag