TypeError:请求路径包含非转义字符,我该如何解决这个问题

时间:2015-06-24 11:00:31

标签: node.js github

/*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的请求,目的是获取指定的列表存储库,但我不断收到上述错误,请帮助

5 个答案:

答案 0 :(得分:17)

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

JavaScript encodeURI() Function

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

答案 1 :(得分:16)

你的"路径"变量包含空格

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

相反它应该是

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

答案 2 :(得分:1)

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

如果希望遵循URL的最新RFC3986,这会保留方括号(用于IPv6),因此在形成可能属于URL的内容(例如主机)时未进行方括号编码,则以下代码段可能帮助:

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); }); }

答案 3 :(得分:0)

  

使用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 :(得分:0)

我在尝试使用Elasticsearch的API时遇到此错误。对我而言,这是由于文档标题中的汉字(在我发送的请求中)。切换为所有英文字符可以解决此问题。

相关问题