将 http 请求的响应保存在变量上并从 node.js 上的函数中提取它

save response of http request on variable and extract it from the function on node.js

只需要 console.log 在变量中输出(让 body 在我的代码中)而不是在控制台中,并且 res.send(现在发送的是“body”而不是“data”)这个变量在 angular/postman 上将请求作为响应。

app.post('/newreq/:uni', (req, res) => {
    pool.getConnection((err, connection) => {
        if(err) throw err
        connection.query('SELECT conn_id,cred_def_id FROM uniConn WHERE uni = ?', [req.params.uni], (err, result, fields) => {
            connection.release() // return the connection to pool
            let connection_id =result[0].conn_id;
            let cred_def_id =result[0].cred_def_id;
            const http = require('http')
            const data = JSON.stringify({
            "connection_id": `${[connection_id]}`,
            "new_request": {
                "requested_attributes": {
                "0_name_uuid": {
                    "name": "score",
                    "restrictions": [
                    {
                        "cred_def_id": `${[cred_def_id]}`
                    }
                    ]
                }
                },
            "requested_predicates": {
            "0_grade_GE_uuid": {
            "name": "score",
            "restrictions": [
            {
            "cred_def_id": `${[cred_def_id]}`
            }
            ]
            }
            }
            }
            })

            const options = {
                hostname: 'localhost',
                port: 9090,
                path: '/new-request/send-request',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': data.length
                }
            }

            let body="";
            req = http.request(options, res => {
                console.log(`statusCode: ${res.statusCode}`)

                res.on('data', d => {
                    process.stdout.write(d)
                    body+=d;
                })
            })

            req.on('error', error => {
                console.error(error)
            })

            req.write(data)
            req.end()
            res.send(data)
        })
    })
});

if i console.log(body: ${body}) 在函数内部,在终端上给出与 process.stdout.write(d) 相同的结果。所以我的问题是如何从函数中提取具有新值的变量,以便可以将其作为响应发送 res.send(body).

擦除res.send(body),将response放入process.stdout.write(d)但名称不同的函数中(不是res,do it response),并更改名称并在路径的起点。

app.post('/newreq/:uni', (req, response) => {
....
....
....
        req = http.request(options, res => {
            console.log(`statusCode: ${res.statusCode}`)

            res.on('data', d => {
                process.stdout.write(d)
                response.send(d)
            })
        })

        req.on('error', error => {
            console.error(error)
        })

        req.write(data)
        req.end()
}