node.js - 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
}
});
推荐阅读
- javascript - 将多个属性绑定到 Vuetify 中的文本字段标签
- python - numpy - 向量化函数:apply_over_axes / apply_along_axis
- oracle - Execute Immediate 语句可以嵌套在另一个 Execute Immediate 中吗
- c# - VS Code C# - 无法在调试控制台中运行控制台应用程序,但可以在集成终端中运行
- excel - 对图像使用 VLOOKUP
- mongodb - 在 Mongo 3.4 中重命名数组文档
- python - 通过具有 NaN 值的数据帧更新数据帧
- javascript - 由于没有 Access-Control-Allow-Origin 标头导致的浏览器错误
- tensorflow - 是否可以在冻结的推理图上用 FusedBatchNorm 替换 Batchnorm?
- reporting-services - 报告服务器上的错误,但 SSRS 或 SSMS 中没有