How is an HTTP POST request made in node.js?

后端 未结 21 2421
南方客
南方客 2020-11-21 23:54

How can I make an outbound HTTP POST request, with data, in node.js?

21条回答
  •  醉酒成梦
    2020-11-22 00:10

    After struggling a lot while creating a low level utility to handle the post and get requests for my project, I decided to post my effort here. Much on the lines of accepted answer, here is a snippet for making http and https POST requests for sending JSON data.

    const http = require("http")
    const https = require("https")
    
    // Request handler function
    let postJSON = (options, postData, callback) => {
    
        // Serializing JSON
        post_data = JSON.stringify(postData)
    
        let port = options.port == 443 ? https : http
    
        // Callback function for the request
        let req = port.request(options, (res) => {
            let output = ''
            res.setEncoding('utf8')
    
            // Listener to receive data
            res.on('data', (chunk) => {
                output += chunk
            });
    
            // Listener for intializing callback after receiving complete response
            res.on('end', () => {
                let obj = JSON.parse(output)
                callback(res.statusCode, obj)
            });
        });
    
       // Handle any errors occurred while making request
        req.on('error', (err) => {
            //res.send('error: ' + err.message)
        });
    
        // Request is made here, with data as string or buffer
        req.write(post_data)
        // Ending the request
        req.end()
    };
    
    let callPost = () => {
    
        let data = {
            'name': 'Jon',
            'message': 'hello, world'
        }
    
        let options = {
            host: 'domain.name',       // Your domain name
            port: 443,                 // 443 for https and 80 for http
            path: '/path/to/resource', // Path for the request
            method: 'POST',            
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(data)
            }
        }
    
        postJSON(options, data, (statusCode, result) => {
            // Handle response
            // Process the received data
        });
    
    }
    

提交回复
热议问题