【问题标题】:TypeError: Request path contains unescaped characters, how can I fix thisTypeError:请求路径包含未转义的字符,我该如何解决这个问题
【发布时间】:2015-09-10 13:13:01
【问题描述】:
/*Making http request to the api (Git hub)
create request
parse responce
wrap in a function
*/
var https = require("https");

var username = 'lynndor';
//CREATING AN OBJECT
var options = {
    host: 'api.github.com',
    path: ' /users/'+ username +'/repos',
    method: 'GET'
};

var request = https.request(options, function(responce){
    var body = ''
    responce.on("data", function(chunk){
        body += chunk.toString('utf8')
    });
    responce.on("end", function(){
        console.log("Body", body);
    });
});
request.end();

我正在尝试创建对 git hub api 的请求,目的是获取指定您的列表存储库,但我不断收到上述错误,请帮助

【问题讨论】:

  • 你在代理后面吗?
  • 没有我的代理服务器没有被检查

标签: node.js github


【解决方案1】:

对于其他情况可能会有所帮助

JavaScript encodeURI() Function

var uri = "my test.asp?name=ståle&car=saab";
var res = encodeURI(uri); 

【讨论】:

  • 谢谢。只有当你使用这种方法时,Facebook graph api 才适用于希伯来语(我猜是所有其他 RTL 语言)。
  • 另一个有用的奇怪用例是当我使用 supertest 和 jest 来测试我的 typescript API 并且我的测试 URL 中有表情符号时。如果不对其进行编码,我无法在该测试中发送请求。
【解决方案2】:

您的“路径”变量包含空格

path: ' /users/'+ username +'/repos',

应该是

path: '/users/'+ username +'/repos',

【讨论】:

  • 在哪里可以获得路径中需要转义的字符列表?
  • 我想我明白了。有时可能需要在通过节点的 http 方法传输之前对字符串 url 进行编码
【解决方案3】:

使用encodeURIComponent()对uri进行编码

decodeURIComponent() 解码uri

这是因为您的 uri 中有保留字符。您需要使用内置的 javascript 函数 encodeURIComponent() 对 uri 进行编码

var options = {
    host: 'api.github.com',
    path: encodeURIComponent('/users/'+ username +'/repos'),
    method: 'GET'
};

要解码编码的 uri 组件,您可以使用 decodeURIComponent(url)

【讨论】:

    【解决方案4】:

    通常,您不想直接使用encodeURI()而是使用fixedEncodeURI()。引用MDN encodeURI() Documentation...

    如果希望遵循更新的 RFC3986 的 URL,它保留方括号(用于 IPv6),因此在形成可能是 URL 一部分的内容(例如主机)时不编码,则以下代码 sn- p 可能会有所帮助:

    function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }

    encodeURIComponent()(来源:MDN encodeURIComponent() Documentation)以及类似的fixedEncodeURIComponent() 函数也存在类似问题。应该使用这些,而不是实际的 encodeURI()encodeURIComponent() 函数调用...

    为了更严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 分隔用途,也可以安全地使用以下字符:

    function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }

    【讨论】:

      【解决方案5】:

      我在尝试访问 Elasticsearch 的 API 时遇到此错误。对我来说,这是由于文档标题中的汉字(在我发送的请求中)。切换到所有英文字符解决了这个问题。

      【讨论】:

        【解决方案6】:

        有时浏览器检查器使用长 JSON 对象的缩写。 在我的例子中,数据包括未转义的字符,例如不应该出现在 http 请求中的“...”。

        【讨论】:

          猜你喜欢
          • 2013-08-03
          • 2019-05-30
          • 2018-07-05
          • 1970-01-01
          • 2021-04-21
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 2023-03-18
          相关资源
          最近更新 更多