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

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

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

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

    Simple and dependency-free. Uses a Promise so that you can await the result. It returns the response body and does not check the response status code.

    const https = require('https');
    
    function httpsPost({body, ...options}) {
        return new Promise((resolve,reject) => {
            const req = https.request({
                method: 'POST',
                ...options,
            }, res => {
                const chunks = [];
                res.on('data', data => chunks.push(data))
                res.on('end', () => {
                    let body = Buffer.concat(chunks);
                    switch(res.headers['content-type']) {
                        case 'application/json':
                            body = JSON.parse(body);
                            break;
                    }
                    resolve(body)
                })
            })
            req.on('error',reject);
            if(body) {
                req.write(body);
            }
            req.end();
        })
    }
    

    Usage:

    async function main() {
        const res = await httpsPost({
            hostname: 'sentry.io',
            path: `/api/0/organizations/org/releases/${changesetId}/deploys/`,
            headers: {
                'Authorization': `Bearer ${process.env.SENTRY_AUTH_TOKEN}`,
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                environment: isLive ? 'production' : 'demo',
            })
        })
    }
    
    main().catch(err => {
        console.log(err)
    })
    

提交回复
热议问题