節點幫助

Hashids NPM(它對開發人員的運作方式)

在現代網路應用中,確保資料安全和隱私是至關重要的。 保護敏感資訊(如資料庫ID或URL)的有效方式之一是使用Hashids,這是個將數字資料轉換為唯一、可逆且加密的雜湊的JavaScript加密庫。 本文探討如何將 Hashids 無縫整合到您的 React 應用程式中,以混淆和解碼識別符號。

什麼是Hashids?

Hashids 是一個小巧但功能強大的庫,可以將數字數據轉換成哈希字串。 主要目標是模糊數字識別符,以防止洩露敏感信息。 此轉換是可逆的,允許在需要時檢索原始數據。 Hashids 是一個 JavaScript 庫,用來將數字轉換成類似 YouTube 的 ID、編碼敏感數據,或者以安全的方式向用戶暴露您的資料庫 ID,亦或只是將數字的 ID 模糊化。

將 Hashids 整合到您的 React 應用中

要將 Hashids 整合到您的 React 應用程式中,請按照下列步驟進行:

步驟 1:安裝 Hashids npm

首先,在您的 React 專案中透過 npm 安裝 Hashids:

npm install hashids
or 
yarn add hashids
npm install hashids
or 
yarn add hashids
SHELL

步驟 2:初始化 Hashids 實例

在您的 React 組件或實用程式文件中,使用 salt 初始化一個新的 Hashids 實例,並且可選擇設置最小哈希長度:

import { useState, useEffect } from 'react';
import Hashids from 'hashids';
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);
  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};
export default MyComponent;
js
JAVASCRIPT

將`'your_salt_here'`替換為您用來自訂雜湊輸出的唯一字串(salt)。

步驟3:編碼和解碼數據

初始化後,您可以使用 Hashids 來編碼和解碼數據。 例如,編碼資料庫 ID:

const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non sequential ids
js
JAVASCRIPT

並將其解碼回原始 ID:

const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
js
JAVASCRIPT

步驟 4:在組件中使用 Hashids

在需要的地方將 Hashids 整合到您的 React 組件中。 例如,將哈希 ID 作為屬性傳遞:

const MyComponent = ({ id }) => {
  const encodedId = hashids ? hashids.encode(id) : '';
  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
js
JAVASCRIPT

在 React 中使用 Hashids 的好處

  • 安全性:Hashids 遮掩數字 ID,提高數據隱私性和安全性工具,防止直接映射到敏感信息。
  • 整合容易性:簡單的 npm 安裝和直接的 API 使 Hashids 容易在 React 應用程式中實施。
  • 靈活性:可自定義的雜湊長度和鹽值提供了靈活性,能夠根據您的應用程式的安全需求調整雜湊。

介紹 IronPDF

IronPDF for Node.js 是 Iron Software 提供的一個強大的 Node.js PDF 庫,允許開發人員在其 .NET 項目中生成和編輯 PDF。 無論您需要從 HTML 創建 PDF、操作現有的 PDF 還是將網頁轉換為 PDF 格式,IronPDF 都能滿足您的需求。

Hashids NPM(適用於開發者的工作原理):圖 1 - IronPDF for Node.js:Node.js PDF 庫

主要功能

HTML 轉 PDF

輕鬆將 HTML 內容轉換成 PDF 文件。 此功能特別適合從網頁內容生成動態 PDF。

URL 轉換為 PDF

直接從網址生成PDF,讓您可以程式化地捕獲網頁內容並將其保存為PDF文件。

PDF 操作

輕鬆合併、拆分和操作現有的 PDF 文件。 IronPDF 提供如附加頁面、拆分文檔等功能。

PDF 安全性

透過加密密碼或應用數位簽章來保護您的 PDF 文件。 IronPDF 提供選項來保護您的敏感文件免受未經授權的訪問。

高品質輸出

生成高品質的 PDF 文件,精確還原文字、圖像和格式。 IronPDF 確保您生成的 PDF 保持對原始內容的忠實性。

跨平台相容性

IronPDF 兼容多種平台,包括 Windows、Linux 和 macOS,使其適合各種開發環境。

簡單整合

輕鬆使用其 npm 套件將 IronPDF 集成到您的 Node.js 應用程式中。 API 有完善的文檔,使將 PDF 生成功能融入您的項目變得簡單明瞭。

安裝

要安裝 IronPDF NPM 軟體包,請使用以下命令:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

使用IronPDF生成PDF文件並使用HashIDs NPM套件

安裝依賴項:首先,使用以下命令創建一個新的 Next.js 專案(如果尚未創建):參考這裡

npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

接著,導航至您的專案目錄:

cd hashids-pdf
cd hashids-pdf
SHELL

安裝所需的軟體包:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
SHELL

建立 PDF

現在,讓我們使用IronPDF創建一個簡單的生成 PDF 的例子。 在您的 Next.js 組件 (例如,pages/index.tsx) 中,新增以下代碼:

PDF 生成 API:第一步是創建一個後端 API 來生成 PDF 文件。 由於 IronPDF 只能在伺服器端運行,因此我們需要創建一個 API,當用戶想要生成 PDF 時進行調用。 在路徑 pages/api/pdf.js 中創建一個文件,並添加以下內容。

IronPDF 需要許可證密鑰,您可以從許可證頁面獲取,並將其放置在下面的代碼中。

// pages/api/pdf.js
import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";
export default async function handler(req, res) {
  try {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    const f = req.query.f;
    const l = initHashids.encode(f);
    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>"
    content+="<p>Input:"+f+"</p>";
    content+="<p>HashID:"+l+"</p>";
    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();
    console.error("data PDF:", data);
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader(
      "Content-Disposition",
      "attachment; filename=awesomeIron.pdf",
    );
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
js
JAVASCRIPT

現在將 index.js 代碼修改如下,以使用 hashID 和 IronPDF

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';
export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    setHashids(initHashids);
  }, []);
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf-hash?f=" + text);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };  
  const handleChange = (event) => {
    seteText(hashids.encode(event.target.value));
    setText(event.target.value);
  };
  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <p>
          HashID of input: {etext}
        </p>        
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family:
            -apple-system,
            BlinkMacSystemFont,
            Segoe UI,
            Roboto,
            Oxygen,
            Ubuntu,
            Cantarell,
            Fira Sans,
            Droid Sans,
            Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
js
JAVASCRIPT

程式碼說明

  1. 從輸入文本框中取得用戶輸入的數字。

  2. 使用 HashID 編碼輸入數字並顯示。

  3. 當使用者點擊生成 PDF 時,輸入的文字會被發送到後端 API,該 API 編碼並生成 PDF 文件。

輸出

Hashids NPM (它如何為開發人員工作): 圖 2

PDF

Hashids NPM(它對開發者如何運作):圖 3

IronPDF 授權

IronPDF

在此處放置授權金鑰:

import {IronPdfGlobalConfig, PdfDocument} from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
js
JAVASCRIPT

結論

將 Hashids 整合到您的 React 應用程式中,是保護敏感資料(如數據庫 ID 或 URL)的實用方法。 通過使用 Hashids,您可以確保識別碼保持安全,同時在需要時保持檢索原始數據的能力。

無論您是在構建小型應用程式還是複雜的企業系統,Hashids 都提供了一個可靠的解決方案,以增強您的 React 項目中的數據隱私和安全性,並且在將遞增的數字編碼為唯一的哈希值方面表現出色。 Hashids 確保即使輸入數字中有重複的模式,仍能生成獨特且不重複的哈希值,維護應用程式中的數據完整性和安全性。

IronPDF 脫穎而出,成為一個強大而多功能的庫,適用於尋求在應用程式中全面 PDF 生成、操作和管理能力的 node.js 開發者。 無論您是在構建網路應用程式、桌面軟體,還是將 PDF 功能整合到企業解決方案中。

Darrius Serrant
全端軟體工程師(WebOps)

Darrius Serrant 擁有邁阿密大學的計算機科學學士學位,目前擔任 Iron Software 的全端 WebOps 行銷工程師。自幼對編程產生興趣,他認為計算機既神秘又易於接觸,使其成為創造力和解決問題的完美媒介。

在 Iron Software,Darrius 享受創造新事物並簡化複雜概念使其更易理解的過程。作為我們的其中一位常駐開發人員,他也自願教導學生,將他的專業知識傳授給下一代。

對 Darrius 來說,他的工作之所以令人滿足,是因為它受到重視並且產生了真正的影響。

< 上一頁
JsdomNPM(它如何為開發者工作)
下一個 >
memcached npm(它如何為開發人員工作)

準備開始了嗎? 版本: 2025.5 剛剛發布

查看許可證 >