URL component encoding in Node.js

前端 未结 3 1885
攒了一身酷
攒了一身酷 2020-12-30 00:30

I want to send http request using node.js. I do:

http = require(\'http\');

var options = {
    host: \'www.mainsms.ru\',
    path: \'/api/mainsms/message/se         


        
相关标签:
3条回答
  • 2020-12-30 00:50

    The best way is to use the native module QueryString :

    var qs = require('querystring');
    console.log(qs.escape('Hello $ é " \' & ='));
    // 'Hello%20%24%20%C3%A9%20%22%20\'%20%26%20%3D'
    

    This is a native module, so you don't have to npm install anything.

    0 讨论(0)
  • 2020-12-30 01:06

    The question is for Node.js. encodeURIcomponent is not defined in Node.js. Use the querystring.escape() method instead.

    var qs = require('querystring');
    qs.escape(stringToBeEscaped);
    
    0 讨论(0)
  • 2020-12-30 01:08

    What you are looking for is called URL component encoding.

    path: '/api/mainsms/message/send?project=' + project + 
    '&sender=' + sender + 
    '&message=' + message +
    '&recipients=' + from + 
    '&sign=' + sign
    

    has to be changed to

    path: '/api/mainsms/message/send?project=' + encodeURIComponent(project) +
    '&sender=' + encodeURIComponent(sender) +
    '&message=' + encodeURIComponent(message) + 
    '&recipients='+encodeURIComponent(from) +
    '&sign=' + encodeURIComponent(sign)
    

    Note:

    There are two functions available. encodeURI and encodeURIComponent. You need to use encodeURI when you have to encode the entire URL and encodeURIComponent when the query string parameters have to be encoded, like in this case. Please read this answer for extensive explanation.

    0 讨论(0)
提交回复
热议问题