11const { findFirstBrac, HTTPbody, JSONbodyParser, queryParser } = require ( './utils.js' )
22
33// Async function to parse the HTTP request
4- async function httpParser ( request ) {
4+ async function httpParser ( request , connection = { } ) {
55 try {
66 const req = { } // Create a new object to store the parsed request
77 const requestString = request . toString ( ) // Convert buffer to string, if necessary
88
9+ // Set client IP address (similar to Express)
10+ req . ip = connection . remoteAddress || '127.0.0.1'
11+
912 // Step 1: Split the request into headers and body by finding "\r\n\r\n"
1013 const headerBodySplit = requestString . split ( '\r\n\r\n' ) // Headers and body are separated by double newline
1114 if ( headerBodySplit . length < 1 ) {
@@ -46,7 +49,7 @@ async function httpParser (request) {
4649 req . query = queryParser ( req . path ) // Parse query string for GET requests
4750 req . path = req . path . split ( '?' ) [ 0 ] // Remove query string from path
4851
49- // Step 4: Handle POST requests (expect a body)
52+ // Step 4: Handle POST and OPTIONS requests
5053 if ( req . method === 'POST' ) {
5154 if ( ! bodyPart ) {
5255 req . body = { }
@@ -61,6 +64,15 @@ async function httpParser (request) {
6164 req . body = { } // Set empty object as fallback
6265 }
6366 }
67+ } else if ( req . method === 'OPTIONS' ) {
68+ // Handle OPTIONS preflight request
69+ req . body = { }
70+ // Store CORS-specific headers for easy access
71+ req . cors = {
72+ origin : req . headers [ 'origin' ] ,
73+ method : req . headers [ 'access-control-request-method' ] ,
74+ headers : req . headers [ 'access-control-request-headers' ]
75+ }
6476 }
6577
6678 return req // Return the fully parsed request object
0 commit comments