Angular 7+如何防止查询参数的特殊字符转换为六进制代码



样本终点:

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/

当我点击上面的端点时。我的url被转换为。。。

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https:%2F%2FsomeOtherService%2FAPIBase.jsp

正如您可以在baseApi参数中看到的/"被转换为"%"2F";以及值";?INT/";也被移除。

如何防止URL将"/"并保留";?INT/";第二参数"内的值的值;baseApi";。

参考

您没有。如果允许的话,它会破坏互联网。

更多详细信息:

  1. 您可以在后端API上使用URL解码将URL转换回标准文本
  2. 永远不要在URL中传递密码。这确实是你能做的最不安全的事情之一

关于第1点:情况并非总是如此,许多API框架会自动解码查询字符串。

如果您需要传递完整的URL,请确保其正确编码:

console.log("https://localhost:4200/test/index.html?" + encodeURIComponent("param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/"));

https://localhost:4200/test/index.html?param1%3Dusername%252passw0rd%26baseApi%3Dhttps%3A%2F%2FsomeOtherService%2FAPIBase.jsp%3FINT%2F

您不能也不应该试图阻止特殊字符的转换。正确的方法是在发送用户之前有意对其进行编码,但在读取数据之前对其进行解码。如果您使用的是javascript,那么您可以通过encodeURIComponent(string)decodeURIComponent(string)来执行此操作。

encodeURIComponent()将接受任何字符串,并将其转换为URL友好格式。

decodeURIComponent()将获取转换后的字符串,并将其改回常规格式。

至于原因为什么你不应该试图阻止它们被转换。。。。。我在这里引用Mozilla:

For example, if a user writes "Jack & Jill", using encodeURIComponent the text will get encoded as "Jack %26 Jill". Without encoding, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

换句话说,假设您允许在URL中使用符号,然后有人创建了一个名为"的用户名杰克&baseApi=evivURL";。您的URL将以结束

http://localhost:4200?username=Jack&baseApi=evilURL&baseApi=https://someOtherService

我不想站在你服务器的立场上,试图猜测正确的baseApi是否是";evivURL";或";someOtherService";。

最新更新