Nodejs Express重定向到可共享的唯一url,客户端JS正在工作



我在Node中使用Express,我想执行以下操作:

如果用户来到页面(hi(或从未存在的新url(hi/wxyz4321(

  • 被重定向到同一页面,但有一个唯一的url,可以共享给其他人(hi/abcd1234(
  • "abcd1234"被附加到一个名为URLS的数组

以下是代码:

const express = require('express');
const app = express();
const http = require('http').Server(app);
const nanoid = require('nanoid');
const fs = require('file-system');
var URLS = [];
var ID = nanoid();
app.use(express.static(__dirname + "/public"))
app.use("/styles",  express.static(__dirname + '/public/css'));
app.use("/scripts", express.static(__dirname + '/public/js'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/public/index.html'));
});
app.get("/*", function(req, res){
var origin= req.url.slice(-21);
//-21 because that is the length of nanoid generated
if(URLS.includes(origin)===false){
URLS.push(ID);
fs.copyFileSync('public/index.html', "public/"+randomID+".html");
//Creates a new html file with the name of ID
//But res.redirect(__dirname + "/public/randomID"); does not work
}
});

提前谢谢。

好吧,我可能已经找到了答案。我的重定向是有效的,但Chrome阻止我加载本地资源,所以我需要将其部署到服务器中才能100%确定。不过,它确实将我重定向到了谷歌和其他现有网站。

const express = require('express');
const app = express();
const http = require('http').Server(app);
const nanoid = require('nanoid');
const fs = require('file-system');
var URLS = [];
var ID = nanoid();
//app.use(express.static(__dirname + "/public"))
//I removed this line, because redirect will not work if user comes to index.html
app.use("/styles",  express.static(__dirname + '/public/css'));
app.use("/scripts", express.static(__dirname + '/public/js'));
//Retaining these two lines, because these lines where the css and js are kept
app.get("/*", function(req, res){
var origin= req.url.slice(-21);
//-21 because that is the length of nanoid generated
if(URLS.includes(origin)===false){
URLS.push(ID);
fs.copyFileSync('public/index.html', "public/"+randomID+".html");
//Creates a new html file with the name of ID
var destination = '<script>window.location.href=' + '"' + __dirname + "/public/"+ randomID + '";</script>';
//var destination = '<script>window.location.href=' + '"' +"https://www.google.com.my/imghp?hl=en&tab=wi&ogbl"+ '";</script>';
//Since this line worked, it will probably work if I test this on a real server
res.send(destination);
//Redirects to the newly created html file
}
});

最新更新