[英]With Node.js, how can I redirect random string paths to the home page?
I've set up a typical node.js server (vanilla, no express, etc) and its works great. 我已经建立了一个典型的node.js服务器(香草,无快递等),并且效果很好。 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.
但是对于我的Web应用程序,我希望能够使用的不是查询字符串,而是表示用户会话ID的简单路径。
For example domain.com/GH34DG2
would be served the same as domain.com. 例如,
domain.com/GH34DG2
服务与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? 如何使用基本的Node.js服务器执行此操作?
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. 当用户在其网络浏览器中键入或粘贴
domain.com/GH34DG2
,我需要服务器来提供索引页面,而不是尝试读取文件domain.com/GH34DG2
,但仍需要读取其他路径,例如样式表,视频等。
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": 如果需要检查路径是否缺少扩展名,然后提供
/index.html
(或home.html或您使用的任何一个),这就是我需要做的所有事情,这是我的“检查主页请求”:
function checkHomeReq(path, ext) {
if (path === "/" || ext == '' )
path = "/index.html";
return path;
}
Just parse the request url. 只需解析请求URL。
Here's a simple server example I just found on google, I added some stuff to handleRequest
: 这是我在Google上找到的一个简单的服务器示例,我向
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? 也许您可以使用md5吗?
in php we have 在PHP中我们有
md5(uniqid(rand()));
in node.js they have a module for MD5 在node.js中,他们有一个MD5模块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.