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

在Deno中使用Opine或其他库获取URL Get参数

在Deno + Opine中获取URL参数的解决方案

注意到你提供的示例URL里,参数是放在**哈希(#)**之后的——这部分内容不会被浏览器发送到后端服务器,只有前端能访问到。下面分两种场景给出处理方法:

一、处理URL查询参数(?后的参数)

如果是笔误,参数本该放在问号(?)之后的查询参数区,Opine自带了便捷的获取方式,直接通过req.query即可读取:

import { opine } from "https://deno.land/x/opine@2.3.4/mod.ts";

const app = opine();

app.get("/auth/confirmation", (req, res) => {
  // 解构获取所需参数
  const { access_token, refresh_token, token_type } = req.query;

  // 后续业务逻辑处理
  console.log("access_token:", access_token);
  console.log("refresh_token:", refresh_token);
  console.log("token_type:", token_type);

  res.send({
    success: true,
    data: { access_token, refresh_token, token_type }
  });
});

app.listen(80, () => {
  console.log("Server running on http://localhost:80");
});

运行命令:

deno run --allow-net your-file.ts

此时用正确格式的URL访问:http://localhost:80/auth/confirmation?access_token=QxsDVgs7OqTrS6_7wuIuQNfE&expires_in=3600&refresh_token=XcaYQFJNfgbnsW3BJjY1ug&token_type=bearer&type=signup,就能正常拿到参数。

二、处理URL哈希(#后的参数)

哈希部分仅存在于浏览器端,后端无法直接获取,需通过前端中转:

  1. 前端解析哈希参数,再传递给后端
// 前端浏览器端代码
const hashParams = new URLSearchParams(window.location.hash.slice(1));
const tokenData = {
  access_token: hashParams.get('access_token'),
  refresh_token: hashParams.get('refresh_token'),
  token_type: hashParams.get('token_type')
};

// 用POST请求把参数发给后端
fetch('/auth/confirmation', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(tokenData)
});
  1. 后端接收前端传递的参数
app.post("/auth/confirmation", async (req, res) => {
  const { access_token, refresh_token, token_type } = await req.json();

  console.log("access_token:", access_token);
  console.log("refresh_token:", refresh_token);
  console.log("token_type:", token_type);

  res.send({ success: true });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:40:50