node.js http 'get' request with query string parameters

前端 未结 5 1579
悲&欢浪女
悲&欢浪女 2020-12-04 15:29

I have a Node.js application that is an http client (at the moment). So I\'m doing:

var query = require(\'querystring\').stringify(propertiesObject);
http.g         


        
5条回答
  •  半阙折子戏
    2020-12-04 15:40

    No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

    const requestUrl = url.parse(url.format({
        protocol: 'https',
        hostname: 'yoursite.com',
        pathname: '/the/path',
        query: {
            key: value
        }
    }));
    

    Then make the request with the formatted url. requestUrl.path will include the query parameters.

    const req = https.get({
        hostname: requestUrl.hostname,
        path: requestUrl.path,
    }, (res) => {
       // ...
    })
    

提交回复
热议问题