I
I
Ivan Ivanovich2020-06-19 11:35:10
Node.js
Ivan Ivanovich, 2020-06-19 11:35:10

Routing element from express in pure node?

Hello. On the one hand, a simple question appeared, and on the other, a complex one, because I have not yet found an answer to it.

There is a simple server without frameworks that receives the address / user

const http = require('http');
http.createServer((req,res)=>{
  if(req.method === 'GET'){

    if(req.url === '/user'){
      res.writeHead(200,{
        'Content-Type': 'text/html'
      });
      res.end(req.url);
    }

  }
}).listen(3000);


And I have a question that I haven't found an answer to yet. Namely, if the address is /user/..., i.e. how to catch the address of a potential user, which can be /user/4, /user/8, /user/999?

In Express, as I understand it, this is done simply / user / *, but I did not find how to implement this in pure node js, so who knows, please tell me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vokhmyanin, 2020-06-19
@IwanQ

Use regular expressions like if( /\/user(\/\d+)?/.test(req.url))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question