I've set up a typical node.js server (vanilla, no express, etc) and its works great. But for my web app, I want to be able to use not a query string, but a simple path to express the user's session ID.
For example domain.com/GH34DG2
would be served the same as domain.com. I decided to attempt this because I've seen other apps use this format, and it's shorter and nicer looking than a query string. Once the user has been served the page, the client will decipher the path and use it to connect to a specific session.
How can I do this with a basic Node.js server?
When the user types or pastes domain.com/GH34DG2
into their web browser, I need my server to serve the index page, not try to read the file domain.com/GH34DG2
, but it still needs to read other paths, like style sheets, videos, etc as usual.
The answer was actual embarrassingly simple I realized. All I need to do if check whether the path was missing an extension and then serve /index.html
(or home.html or whichever one you use), here's my "Check Home Request":
function checkHomeReq(path, ext) {
if (path === "/" || ext == '' )
path = "/index.html";
return path;
}
Just parse the request url.
Here's a simple server example I just found on google, I added some stuff to handleRequest
:
var http = require('http');
const PORT=8080;
function handleRequest(request, response){
// parse request.url to pull out the session_id
var session_id = request.url.split('/')[1];
// do something with session_id
// serve page/data/whatever
response.end('It Works!! Path Hit: ' + request.url);
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
Maybe you can use something called md5?
in php we have
md5(uniqid(rand()));
in node.js they have a module for MD5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.