TypeError: Request path contains unescaped characters, how can I fix this

前端 未结 5 623
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 19:18
/*Making http request to the api (Git hub)
create request
parse responce
wrap in a function
*/
var https = require(\"https\");

var username = \'lynndor\';
//CREATIN         


        
相关标签:
5条回答
  • 2021-01-03 19:54

    I was getting this error while trying to hit Elasticsearch's API. For me, it was due to Chinese characters in the Document's Title (in the Request I was sending). Switching to all English characters fixed the issue.

    0 讨论(0)
  • 2021-01-03 20:08

    Your "path" variable contains space

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

    Instead it should be

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

    0 讨论(0)
  • 2021-01-03 20:11

    Typically, you do not want to use encodeURI() directly. Instead, use fixedEncodeURI(). To quote MDN encodeURI() Documentation...

    If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:

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

    There is a similar issue with encodeURIComponent() (source: MDN encodeURIComponent() Documentation), as well as a similar fixedEncodeURIComponent() function. These should be used, rather than the actual encodeURI() or encodeURIComponent() function calls...

    To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

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

    0 讨论(0)
  • 2021-01-03 20:20

    Use encodeURIComponent() to encode uri

    and decodeURIComponent() to decode uri

    Its because there are reserved characters in your uri. You will need to encode uri using inbuilt javascript function encodeURIComponent()

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

    to decode encoded uri component you can use decodeURIComponent(url)

    0 讨论(0)
  • 2021-01-03 20:21

    for other situation can be helpful

    JavaScript encodeURI() Function

    var uri = "my test.asp?name=ståle&car=saab";
    var res = encodeURI(uri); 
    
    0 讨论(0)
提交回复
热议问题