【问题标题】:How to capture response body from API in NodeJS如何从 NodeJS 中的 API 捕获响应体
【发布时间】:2018-10-19 14:41:43
【问题描述】:

我是NodeJS 的新手,我正在练习一个小项目。 我有这段代码通过 API 端点向我的NodeJS express 服务器发送请求。

        var XHR = new XMLHttpRequest();
        var merchants = ['f6ea7039-de8e-4403-bb63-d348dd502dc8', 'c2a08bfa-db18-4e08-8a08-f4e04dea7e58',
                            'e02ed2a4-06f4-403b-ad1e-f72b55e0681d'];
        //set up the transfer request
        XHR.open('POST', apiUrl + '/transfer', true);

        XHR.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        XHR.withCredentials = true;

        var data = JSON.stringify({
            //merchantId: merchants[(Math.floor((Math.random() * 200))/100)],
            merchantId: 'f6ea7039-de8e-4403-bb63-d348dd502dc3',
            amount: (Math.floor((Math.random() * 1000) + 100)/100),
            currency: 'EUR',
            description: 'Book 

        // Define what happens on successful data submission
        XHR.addEventListener("load", function(event) {
            console.log(event);
            // execute callback once response is received
            if (event.target.status === 200) {
                done(XHR.response);
            }
        });

        XHR.send(data)

在我的服务器端我有这个代码:

function getMerchantName(query) {
                return new Promise(function(resolve,reject){

                    pool.query(query, [tr.merchantId], function(error, result){

                        // error ? reject(error) : resolve(result);
                        if(result[0]){
                            return resolve(result);
                        }else{
                            return reject(error);
                        }

                    });

                });
            }

            getMerchantName(sql)
            .then(result => {
                tr.secondaryName = result[0].mName;
                console.log("Secondary Name: ",tr.secondaryName);
                conn.release();
                getUrl();
            })
            .catch(function(error){
                console.log('Rejected', error);
                // res.send(400, {message: 'Merchant Not Found'});
                res.status(403).send({message: 'Merchant Not Found'});
            });

因此,当找不到merchant id 时,我会(通过promise 的捕获)对res.status(403).send({message: 'Merchant Not Found'}); 进行响应

我只能通过XHR.addEventListener load 事件访问错误状态,而不能通过响应正文访问。 如何访问此响应正文以在客户端显示?

【问题讨论】:

    标签: node.js api response http-status-code-403


    【解决方案1】:

    我认为你应该使用express bodyparser:

    在初始化期间:

    app.use(bodyParser.json())
    

    这是一个示例请求处理程序:

    app.get('/', (req, res) => console.log(req.body))
    

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2017-10-30
      • 2019-09-23
      • 2023-01-24
      • 1970-01-01
      相关资源
      最近更新 更多