Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have to develop a web server without Express and I was wondering if there was any way to use the way Express routes for example the /path/:example, so I could access that with /path/test and the query variable example would be "test".

Currently I'm just using basic query parameters, /path?example=test, but I would like to be able to reduce it to the above.

Is that not possible unless it's in Express? I can't use any routing module.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
143 views
Welcome To Ask or Share your Answers For Others

1 Answer

Ok, so I stand by my comment that your client is making an ill-informed decision. Yes, it's possible to do routing w/o Express, but it will require a lot more custom code and doesn't provide extra value. Further, there are a LOT of really good tools in the same ecosystem (e.g. helmet) that make your apps better, easier to build and maintain, and more secure.

That said, if the client is set on this path of madness and you don't want to "fire" your customer, here's the guts of what you have to do:

const http = require('http');
const url = require('url');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  const requestUrl = url.parse(req.url);
  const path = requestUrl.pathname;

  const parts = path.split('/').slice(1);

  // This is really brittle, but assuming you know it's going to be 2 parts remaining after the above..

  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end(parts[1]);
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Now, that's the basics. Obviously, if you want to essentially re-do the routing Express provides, you'll want to add in a lot more logic to handle parsing the string the way you want to and assigning route handlers and all that stuff. Sorry, it's not easy, but that's why so many folks use Express (or Connect, or other routing modules).

Some other things that might make this easier for you... Express is open source, so read their source code and see how they're doing what you need done, then implement it yourself. I'm not saying copy it verbatim (if you do that, you might as well just use their module...), but get inspiration.

For example, there's a utility they use called path-to-regexp that converts the '/path/:example' string into a regex that can be used to test an incoming URL. Reading that source code might help you understand what they're doing better.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...