0

I am able to write code using node and express for the below request:

http://localhost:8000/users/1

The code is :

const express = require('express')
const app = express()

app.get('/users/:userId', (req, res) => {
  res.send(req.params)
})

I want to do the same using http module:

var http = require('http');

//create a server object:
let server = http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(8000); //the server object listens on port 8080

What is the correct approach for this?

learner
  • 6,062
  • 14
  • 79
  • 139

1 Answers1

1

You will need to:

  • Read req.method and see it's the method you expect, and if not error.
  • Read req.url, and use a path matching library, such as path-to-regexp or regular expression to validate the path and extract parameters.

If you want actual code samples for this, read the source of these frameworks.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • Can you please share me code sample. I am trying to check this `https://nodejs.org/api/http.html` but I am not able to find correct approach to solve this. – learner May 23 '23 at 20:41
  • @learner there is no built in way to do this automatically for you. You are basically making your own mini-framework. I also don't want to write all the code for you. If you dont' want to write the code, use a framework. – Evert May 23 '23 at 21:27
  • I have tried it, but the chai test script is failing now. https://stackoverflow.com/questions/76318987/getting-unhandledpromiserejectionwarning-while-running-testcase This is the issue I am getting, can you please help me how to fix this. – learner May 23 '23 at 22:35