首页 > 解决方案 > Nodejs - res.render/send 不适用于带有等待的异步功能

问题描述

我编写了一些代码来使用他们的 API 在 JIRA 上创建问题。票证创建得很好,但我正在努力将这个或任何错误传达给用户。我尝试在这里使用答案无济于事(如代码中所示)。

基本上,在点击提交后,我返回了没有任何结果的基本页面,因此无法通知用户他们的票是否已创建。我怀疑异步把它搞砸了,所以我在上下文中包含了更多内容。

/* Modules */
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const http = require('machinepack-http');

/* app setup */
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

app.get('/', function(req, res){    
    res.render(path.join(__dirname+'/index'), {results: ''});
});
app.listen(2005, function () {
  console.log('Jira Portal listening on port 2005');
});
app.post('/submit', function(req, res){ 
    addAsync(req, res).then((result) => {
        console.log("****** JIRA response: ");
        console.log(result);// standard JIRA API response
        var issueName = result.body.split(",")[1].split(":")[1].replace(/"/g,"");//gets issue name if success (eg. TEST-007)
        var issueDesc = result.body.split(",")[1].split(":")[2].replace(/"/g,"").replace(/\}/g,"");//gets error description if error
        if(result.body.split(",")[0].split(":")[0].replace(/"/g,"").replace(/\{/g,"") == "errorMessages"){
            console.log('ERROR:' + issueDesc); //ERROR:The reporter specified is not a user.
            /*
            * This is not working, html is outputting the correct html code
            * but the user never sees it on their end.
            */
            res.render(path.join(__dirname+'/index'), {results: 'ERROR:' + issueDesc}, 
                function(err, html){
                    if(err){ console.log(err); }
                    console.log(html);//this html output is correct
                    res.status(200).send(html);//never see this html on browser
                }
            );
        }else{
            // Not tested yet, but assuming probably the same issue occurs
            console.log('Created ticket ' + issueName + '. To see this ticket, go to ' + _JIRA_HOST + 'browse/' + issueName);
            return res.render(path.join(__dirname+'/results'), {results: 'Created ticket ' + issueName + '. To see this ticket, go to ' + _JIRA_HOST + 'browse/' + issueName});
        }
    });
});
async function addAsync(req, res){
    return await(createJiraIssue(req, res)); //http post method to JIRA (contains a promise)   
}

根据要求,该createJiraIssue()功能(我希望不需要减少问题中发布的代码量)。

function createJiraIssue(req, res){
    var login_data = _JIRA_USER + ":" + _JIRA_PW;
    login_data = Buffer.from(login_data).toString('base64');
    return new Promise((resolve, reject) => {
        http.sendHttpRequest({
            url: '/rest/api/2/issue/',
            baseUrl: _JIRA_HOST,
            method: 'post',
            body:{
                "fields": {
                    "project": {
                        "key": _JIRA_PROJECT
                    },
                    "summary": req.body.summary,
                    "description": req.body.desc,
                    "issuetype": {
                        "name": _JIRA_ISSUE_TYPE
                    },
                    "reporter": {
                        "name": req.body.user
                    },
                    "components": [{
                        "id": req.body.component.split('&')[0]
                    }],
                    "labels": [req.body.area]
                }
            },
            headers: {
                "Authorization": "Basic " + login_data,
                'Content-Type': 'application/json'
            }
        }).switch({
            error: function(err){ return reject(err); },
            non200Response: function(result){ resolve(result); },
            requestFailed: function(){ return reject("request failed"); },
            success: function(result){ resolve(result); },
        });/*End switch*/
    });/*End Promise*/
}

样本结果

{ statusCode: 400,
  headers: 
   { server: 'servername',
     date: 'Tue, 24 Jul 2018 13:02:05 GMT',
     'content-type': 'application/json;charset=UTF-8',
     'transfer-encoding': 'chunked',
     connection: 'close',
     'set-cookie': 
      [ 'cookie info' ],
     'x-arequestid': 'requestid',
     'x-anodeid': 'nodeid',
     'x-asen': 'SEN-xxxxxxxx',
     'x-seraph-loginreason': 'OK',
     'x-asessionid': 'sessionid',
     'x-ausername': 'username',
     'cache-control': 'no-cache, no-store, no-transform',
     'x-content-type-options': 'nosniff' },
  body: '{"errorMessages":[],"errors":{"reporter":"The reporter specified is not a user."}}' }

标签: javascriptnode.js

解决方案


为什么要使用addAsync函数,没用就createJiraIssue直接在里面使用request function并提出请求function async

/* Modules */
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const http = require('machinepack-http');

/* app setup */
app.use(bodyParser.urlencoded({ extended: true })); 
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

app.get('/', function(req, res){    
    res.render(path.join(__dirname+'/index'), {results: ''});
});
app.listen(2005, function () {
  console.log('Jira Portal listening on port 2005');
});
app.post('/submit', async function(req, res){ 
  try{
        const result =  await createJiraIssue(req, res);
        console.log("****** JIRA response: ");
        console.log(result);// standard JIRA API response
        var issueName = result.body.split(",")[1].split(":")[1].replace(/"/g,"");//gets issue name if success (eg. TEST-007)
        var issueDesc = result.body.split(",")[1].split(":")[2].replace(/"/g,"").replace(/\}/g,"");//gets error description if error
        if(result.body.split(",")[0].split(":")[0].replace(/"/g,"").replace(/\{/g,"") == "errorMessages"){
            console.log('ERROR:' + issueDesc); //ERROR:The reporter specified is not a user.
            /*
            * This is not working, html is outputting the correct html code
            * but the user never sees it on their end.
            */
            res.render(path.join(__dirname+'/index'), {results: 'ERROR:' + issueDesc}, 
                function(err, html){
                    if(err){ console.log(err); }
                    console.log(html);//this html output is correct
                    res.status(200).send(html);//never see this html on browser
                }
            );
        }else{
            // Not tested yet, but assuming probably the same issue occurs
            console.log('Created ticket ' + issueName + '. To see this ticket, go to ' + _JIRA_HOST + 'browse/' + issueName);
            return res.render(path.join(__dirname+'/results'), {results: 'Created ticket ' + issueName + '. To see this ticket, go to ' + _JIRA_HOST + 'browse/' + issueName});
        }

      }
      catch(e){
          console.log("error",e);
      }
});

推荐阅读