首页 > 解决方案 > Nodejs Express 重定向到可共享的唯一 url,客户端 JS 工作

问题描述

我在 Node 中使用 Express,我想做这些:

如果用户访问页面 (hi) 或从未存在的新 url (hi/wxyz4321)

以下是代码:

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
    }
});

提前致谢。

标签: node.jsexpress

解决方案


好的,我可能已经找到我的答案了。我的重定向有效,但 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
    }
});

推荐阅读