【问题标题】:decodeUri not working with res.json expressdecodeUri 不适用于 res.json express
【发布时间】:2018-08-23 20:35:53
【问题描述】:

有一个快速应用程序,可以将经过处理的 url 保存到 mongodb 数据库,我想使用 decodeURI() 在 res.json 中呈现解码后的 url,但它不能按预期工作,只能返回编码版本。如果我做一个 res.send(decodeURI(url)) 它工作。如何让 res.json 发送解码后的 url。

        // Create a url object with escaped and trimmed data.
    var Url = new UrlModel(
      { url: req.body.url }
    );


    if (!errors.isEmpty()) {
        // There are errors. Render the form again with error messages.
        res.render('index', { errors: errors.array()});
    return;
    }
    else {
        // Data from form is valid.
        // Check if Url with same name already exists.
        UrlModel.findOne({ 'url': req.body.url })
            .exec( function(err, found_url) {
                 if (err) { return next(err); }

                 if (found_url) {
                     // Url exists, redirect to its detail page.
                     res.json({"original_url": decodeURI(found_url.url) });
                     //res.send(decodeURI(found_url.url))

                 }

更新:

我的问题可能不清楚。我的输入来自 mongodb,其格式为

https://www.facebook.com

所以我想转换它的 html 实体,我不认为 decodeUri 会这样做。 我从这段代码中得到的结果

res.json({original_url:found_url.url, decoded: decodeURI(found_url.url) });

{"original_url":"https://www.facebook.com","decoded":"https://www.facebook.com"}

所以 url 中的 // 没有被转换为 // 。是否有一些核心 javascript 函数可以执行此操作,还是我必须使用带有 regx 的函数并替换?

【问题讨论】:

    标签: javascript json node.js express


    【解决方案1】:

    问题更新后更新。

    在 JavaScript 中,您可以使用一些函数来完成类似的转换:encodeURIencodeURIComponent,以及它们对应的 decodeURIdecodeURIComponentencodeURI 用于对完整的 URL 进行安全编码,因为它不会对协议、主机名或路径进行编码; encodeURIComponent 将对所有内容进行编码。

    您在编辑后的问题中显示的内容(据我所知)与 JavaScript 无关;您需要先让后端对该字符串进行消毒,然后再将其发送回给您。

    如果更新后端不是一个选项,你可以尝试这样的事情:

    unescape('https://www.facebook.com'.replace(/&#x/g, '%').replace(/;/g, ''))
    

    这会将这些实体解码为它们的实际字符,但它不应该是一个永久的解决方案,因为它是marked as deprecated


    原始回复。

    encodeURI 和 decodeURI 完全没有问题。您完全确定它没有按预期返回吗?中间是否有其他东西再次对其进行编码?

    我用 Postman 测试了这个小 sn-p。

    const express = require('express');
    const app = express();
    
    const encoded = encodeURI('http://example.com?query=ÅÍÎÏ˝ÓÔÒÚÆ☃');
    const decoded = decodeURI(encoded);
    
    app.get('/json', (req, res) => res.json({ encoded, decoded }));
    
    app.listen(3000, () => console.log('Example app listening on port 3000!'));
    

    【讨论】:

    • 感谢编辑我上面的问题以添加更多信息。这是我需要转换的 html 实体。
    • 更新回复以匹配您的问题。 TL;DR 使用 unescape + replace 作为解决方法,但在您的后端进行更新。
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2021-06-30
    相关资源
    最近更新 更多