如何使用NodeJ的“ https”模块解决此https请求?

时间:2019-02-05 06:57:47

标签: node.js curl https

我正在尝试编写一个脚本来检测和删除不再需要的GitHub存储库,删除部分遇到了一些麻烦。

我已经编写了一个辅助函数,该函数将向api.github.com发送DELETE请求并返回Promise。但是问题是,使用此功能时,我收到400错误的请求,但相同的请求在curl上工作正常。 (响应应为204 No Content。)。

这是“ https”版本。路径变量很好,我已经检查了它。它返回一个400错误的请求。

const deleteRepo = (n, token) => {
    const path = `repos/${n}`
    console.log(path)
    const options = {
        method: 'DELETE',
        hostname: 'api.github.com',
        path,
        headers: {
            'Accept': '*/*',
            'Authorization': `Basic ${Buffer.from(token).toString('base64')}`,
            'User-Agent': 'curl/7.52.1'
        },
    }

    return new Promise((resolve, reject) => {
        const req = https.request(options, res => {
            body = ''
            res.on('data', c => body += c)

            if (res.statusCode == 204) {
                console.log('Deleted ', path)
                res.on('end', () => {
                    reject(body)
                })
                resolve()
            } else {
                console.log('Error deleting ', path, res.statusCode, res.statusMessage)
                res.on('end', () => {
                    reject(body)
                })

            }
            res.on('error', (e) => reject(e))
        });
        req.end()

        console.log(req)
    })
}

与curl相同的功能按预期工作,返回204 No Content。

const cmd = `curl -v -u ${token} -X DELETE https://api.github.com/repos/${n}`
console.log('Deleting ', path)
console.log(child_process.execSync(cmd, (e, stdout, stderr)=> {
    if (e) {
        console.error(e);
        throw e;
    }

    console.log('stdout ', stdout);
    console.log('stderr ', stderr);
}))

0 个答案:

没有答案
相关问题