You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中获取URL等号后内容及提取token存入db

Solution for Extracting URL Parameters (Including Token) and Saving to Database in TypeScript

Alright, let's break down how to tackle this problem step by step—from parsing the URL to safely storing the token in your database, all with TypeScript's type safety in mind.

1. Parsing the URL & Extracting Parameters

The native URL API is your best friend here—it’s fully supported in TypeScript and simplifies query string/hash fragment parsing.

Example: Extract Token from Query Parameters

If your URL looks like https://yourapp.com/?token=abc123xyz&user=456, here’s how to pull out the token:

// In browser environments, use window.location.href instead of a hardcoded string
const targetUrl = new URL("https://yourapp.com/?token=abc123xyz&user=456");

// Directly grab the token by parameter name
const token = targetUrl.searchParams.get("token");

// Add type checks to avoid runtime issues
if (token) {
  console.log("Extracted token:", token);
} else {
  console.error("No token found in URL query parameters");
}

If Your Token Lives in the URL Hash

Some apps store tokens in the hash (e.g., https://yourapp.com/#token=abc123xyz). Here’s how to handle that:

const urlWithHash = new URL("https://yourapp.com/#token=abc123xyz");
// Slice off the leading # and parse the hash as a query string
const hashParams = new URLSearchParams(urlWithHash.hash.slice(1));
const tokenFromHash = hashParams.get("token");

if (tokenFromHash) {
  console.log("Token from hash:", tokenFromHash);
}

Before saving to the database, it’s smart to validate the token (e.g., check if it’s a valid JWT):

import jwt from "jsonwebtoken"; // Install via npm install jsonwebtoken @types/jsonwebtoken

function isTokenValid(token: string): boolean {
  try {
    // Replace with your actual secret/public key
    jwt.verify(token, "your-app-secret-key");
    return true;
  } catch (error) {
    console.error("Invalid token:", error);
    return false;
  }
}

// Usage
if (token && isTokenValid(token)) {
  // Proceed to save the token
}

3. Saving the Token to a Database

Let’s cover two common approaches: a raw database client (PostgreSQL example) and a type-safe ORM like Prisma.

Approach 1: Raw PostgreSQL Client (pg Library)

First install dependencies:

npm install pg @types/pg

Then write the TypeScript code to save the token:

import { Pool } from "pg";

// Initialize a connection pool (reuse this across your app)
const dbPool = new Pool({
  user: "your-db-user",
  host: "localhost",
  database: "your-db-name",
  password: "your-db-password",
  port: 5432,
});

async function saveToken(token: string, userId?: string) {
  try {
    const result = await dbPool.query(
      `INSERT INTO user_tokens (token, user_id, created_at) 
       VALUES ($1, $2, NOW()) 
       RETURNING *`,
      [token, userId]
    );
    console.log("Token saved successfully:", result.rows[0]);
    return result.rows[0];
  } catch (error) {
    console.error("Failed to save token:", error);
    throw error; // Re-throw to handle upstream if needed
  }
}

// Usage (after extracting and validating the token)
if (token && isTokenValid(token)) {
  await saveToken(token, targetUrl.searchParams.get("user"));
}

Approach 2: Type-Safe ORM (Prisma)

Prisma eliminates manual SQL and adds built-in type safety. First set up your Prisma schema:

model UserToken {
  id        Int      @id @default(autoincrement())
  token     String   @unique // Prevent duplicate tokens
  userId    Int?
  createdAt DateTime @default(now())
  User      User?    @relation(fields: [userId], references: [id])
}

Then write the TypeScript code:

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

async function saveTokenWithPrisma(token: string, userId?: number) {
  try {
    const savedToken = await prisma.userToken.create({
      data: {
        token,
        userId,
      },
    });
    console.log("Token saved via Prisma:", savedToken);
    return savedToken;
  } catch (error) {
    console.error("Prisma save error:", error);
    throw error;
  } finally {
    await prisma.$disconnect(); // Clean up connection
  }
}

// Usage
if (token && isTokenValid(token)) {
  await saveTokenWithPrisma(token, parseInt(targetUrl.searchParams.get("user") || ""));
}

Key Best Practices

  • Type Safety: Always check if token is not null before proceeding—TypeScript will help catch these gaps.
  • Security: Use SSL for database connections, and consider encrypting sensitive tokens before storing them.
  • Error Handling: Wrap database operations in try/catch blocks to handle connection issues or duplicate token errors.

内容的提问来源于stack exchange,提问作者Giovanni Dias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:19:27