首页 > 解决方案 > 从 HTTP 引用 URL 中提取字段/属性

问题描述

我有这个示例 URL(引用)。

http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback

我需要提取字段“状态”的值。(在这种情况下将是“某种状态”)。我试图用 substr() 来做,但我必须计算 base64 编码子字符串的长度。(这不是动态或安全的)

作为替代方案,我会将其转换为 JSON 并尝试从 JSON 中提取它。

非常感谢。

标签: javascriptnode.jsregexrestify

解决方案


在处理标准数据格式时,不要尝试使用正则表达式或 substr 来滚动您自己的解析器。这是一个网址。查找现有的 URL 解析器。

Node.js与一个一起分发

const referer = "http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback";
const parsed_url = new URL(referer);
const state = parsed_url.searchParams.get("state");
console.log(state);

NB: As the documentation mentions, Node has two URL parsers. The URL global and the url module which you can require. You need a relatively new version of Node to use the URL global. If you don't have it, then upgrade your Node.js install.

As an alternative, I would convert it to JSON and try to extract it from JSON.

This would be a red herring. To convert it to JSON you would first need to parse it. Once you have the parsed data, it would be still to convert it to JSON only to immediately convert it back to the parsed data you already have.


推荐阅读