/*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();
Run Code Online (Sandbox Code Playgroud)
我试图创建一个git hub api的请求,目的是获取指定的列表存储库,但我不断收到上述错误,请帮忙
小智 28
对于其他情况可能会有所帮助
var uri = "my test.asp?name=ståle&car=saab";
var res = encodeURI(uri);
Run Code Online (Sandbox Code Playgroud)
小智 19
您的"路径"变量包含空格
path: ' /users/'+ username +'/repos',
相反它应该是
path: '/users/'+ username +'/repos',
使用
encodeURIComponent()
来编码URI并
decodeURIComponent()
解码uri
这是因为您的 uri 中有保留字符。您将需要使用内置的 javascript 函数对 uri 进行编码encodeURIComponent()
var options = {
host: 'api.github.com',
path: encodeURIComponent('/users/'+ username +'/repos'),
method: 'GET'
};
Run Code Online (Sandbox Code Playgroud)
解码您可以使用的编码 uri 组件 decodeURIComponent(url)
通常,您不想encodeURI()
直接使用。 相反,使用fixedEncodeURI()
. 引用MDNencodeURI()
文档...
如果您希望遵循更新的 URL RFC3986,该 RFC3986 保留方括号(用于 IPv6),因此在形成可能属于 URL 一部分的内容(例如主机)时不进行编码,以下代码片段可能会有所帮助:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
encodeURIComponent()
(来源:MDNencodeURIComponent()文档)以及类似的函数也存在类似的问题fixedEncodeURIComponent()
。应该使用这些,而不是实际的encodeURI()
或encodeURIComponent()
函数调用......
为了更严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 分隔用途,也可以安全地使用以下字符:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }