簡體   English   中英

URL 使用JavaScript訪問文件的參數

[英]URL Parameters for accessing files using JavaScript

在我的 node.js 項目中,我有一個 server.js 和一個文件夾“views”,其中包含一個名為 index.html 的文件,所以現在當有人訪問example.com (或example.com/index.html )時,他們會 go 進行索引。 js,好吧,我正在嘗試保護它,以便僅通過特定鏈接授予訪問權限,例如

example.com -> 將您帶到 access_denied.html 和example.com/client={code-that-i-assign}示例example.com/client=th9wdn298n3d2

我嘗試使用 URLparams 來做,但我做不到,有人可以幫我解決這個問題嗎?

function api() {
    const apikey = "";
    const searchselect = window.location.search;
    const urlsearchparams = URLSearchParams(searchselect);
    urlsearchparams.has(apikey).then(return true);

}

我想理解你想檢查 url 中是否有一個 get 變量,比如輸入和使用確定頁面的令牌,為此你必須在服務器中為頁面提供服務的中間件之前使用 express 中間件.js 文件,例如:

app.use(function (req, res, next) { // controlla il token
  const foo = req.query.foo;

  if (foo !== 'MAGIC_KEY' /* or what control you want to do */) next(Error('Nope'));
  else next();
});
app.use(express.static(path.join(__dirname, 'public')));

並使用此參數調用頁面/?foo=MAGIC_KEY

使用您的代碼進行編輯:

const path = require("path");
const express = require("express");
const app = express();

// make all the files in 'public' available
// https://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));

// this is the code I writed before
app.use(function (req, res, next) { //  /?foo=MAGIC_KEY
  const foo = req.query.foo;

  if (foo !== 'MAGIC_KEY') next(Error('Nope'));
  else next();
});

// This is the middleware that serve the index
// https://expressjs.com/en/starter/basic-routing.html
app.get("/", (request, response) => {
  response.sendFile(__dirname + "/views/index.html");
});

app.use(express.static(path.join(__dirname + "/views/gg.txt")));

const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

在這種特殊情況下,您可以一個一個地管理請求,但這通常不是一個很好的解決方案。 只需將\key替換為您需要的任何內容。 如果您登陸example.com ,它將以access-denied.html響應,但是,例如請求example.com/key將使您進入索引。

const path = require("path");
const express = require("express");
const app = express();

// This is the middleware that serve the index
app.get("/", (request, response) => {
  response.sendFile(__dirname + "/public/access-denied.html");
});

app.get("/key", (request, response) => {
  response.sendFile(__dirname + "/public/index.html");
});

app.use(express.static(path.join(__dirname + "/public/gg.txt")));

const listener = app.listen(process.env.PORT, () => {
  console.log("Your app is listening on port " + listener.address().port);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM