URL component encoding in Node.js

前端 未结 3 1913
攒了一身酷
攒了一身酷 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 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.

提交回复
热议问题