来自节点js服务器的错误,但未指向任何特定文件

时间:2019-06-09 13:32:45

标签: javascript node.js api express nodemon

  • 我在一个域中有一个api,在另一个域中有所有其他api。
  • 因此在SprtsAppConstatnts.js中,我对所有域进行了硬编码。
  • 当我打印然后出现在document.js中的formatUrl --->时,它打印的是正确的域 然后formatUrl ---> http://players.com/run/kit/?id=090000000009009093292390230923
  • SportsResUtility.js文件中URL ===>中的一个显示的域不正确 网址===> http://sports.com/tes/run/kit/?id=090000000009009093292390230923
  • 因为它从文件SprtsAppConstatnts.js中获取了硬编码值exports.DATA_DNS_NAME = "http://sports.com";
  • 不确定如何在SportsResUtility.js中添加条件,因此仅对于此路径,它应该添加此域http://players.com
  • 我在服务器日志中看到了两个错误,不确定从哪个文件传来。 (node:30332) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent. (node:30332) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  • 是否有任何方法可以从哪个文件中查找文件。我是否需要安装其他任何软件包进行调试。
  • 在下面提供我的代码段和沙箱

SprtsAppConstatnts.js

exports.GET_JWT_TOKEN_URL = 'https://credentials.com';

exports.DATA_DNS_NAME_CONTENT_CENTRAL = "http://players.com";
// "http://usersports.com"; // "http://fddfdfdf.main.com:9080";  // dp-rest-apis-url


exports.DATA_DNS_NAME = "http://sports.com"; // "http://fddfdfdf.main.com:9080";  // dp-rest-apis-url

exports.CUST_MICRO_SVC_DNS_NAME = "http://fddfdfdf.main.com";

exports.SERVICE_SERVER_DNS_NAME = 'http://sports.com';

exports.REST_API_dfdfdfdf_DNS_NAME = 'https://dfdfdfdf.com';

SportsResUtility.js

const axios = require('axios');

const SprtsAppConstatnts = require('../../constants/SprtsAppConstatnts');

const credentials = require('../../internals/credentials.json');

const authUtil = require('./AuthorizationUtil');

module.exports =
{
  callService : (res, url, uri) => {

    var formatUrl;

    if(uri){
       formatUrl = uri + url;
    }
    else{
       formatUrl = SprtsAppConstatnts.DATA_DNS_NAME + url;
    }

    console.log("  URL ===> ", formatUrl);

      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      //console.log( " local Token => ", authJwtToken);
      if(!credentials.auth.jwtToken) {

      axios.get(SprtsAppConstatnts.GET_JWT_TOKEN_URL, {
          auth: {
            username: credentials.auth.racfId, password: credentials.auth.password
          }
        })
        .then((jwtResponse) => {
          //console.log('------jwtResponse Res------>>>> ', jwtResponse)
          var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
          //console.log('------Token Res------>>>> ', jwtToken)
          axios.get(formatUrl,{ headers: {"Authorization" : jwtToken}})
            .then((response) => {
              return res.json(response.data);
            })
            .catch( (error) => {
              if(error.response){
                return res.send(error.response.data);
              }
              else{
                return res.send(error);
              }

            })

        })
        .catch( (error) => {
            return res.send(error);
        })      
        ;
    }
    else {
      var authJwtToken = `Bearer ${credentials.auth.jwtToken}`;
        axios.get(formatUrl,{ headers: {"Authorization" : authJwtToken}})
            .then((response) => {
              return res.json(response.data);
            })
            .catch( (error) => {
              if(error.response){
                return res.send(error.response.data);
              }
              else{
                return res.send(error);
              }
            })

    }

  },

  callServiceWithDns : (res, url) => {
    axios.get(url)
        .then((response) => {
          return  res.json(response.data);
        })
        .catch( (error) => {
          return res.json(error);
        });
  },

  postServiceCall : (res, url, reqJSON) => {
    var formatUrl = SprtsAppConstatnts.DATA_DNS_NAME + url;
    axios.post(formatUrl, reqJSON)
        .then((response) => {
          console.log("===Log=====> "+response.data.message);
          return res.json(response.data);
        })
        .catch( (error) => {
          return res.json(error);
        });
  },

  callServiceByFilters : (res, url, hostName, helper, fbNum, policyId) => {

    var formatUrl = SprtsAppConstatnts.DATA_DNS_NAME + url;
    if(hostName) {
      formatUrl = hostName + url;
    }
    console.log("  URL  ===> ", formatUrl);
    //console.log(" Type of ", (typeof helper));

    axios.get(SprtsAppConstatnts.GET_JWT_TOKEN_URL, {
      auth: {
        username: credentials.auth.racfId, password: credentials.auth.password
      }
    })
    .then((jwtResponse) => {
      var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
      axios.get(formatUrl,{ headers: {"Authorization" : jwtToken}})
        .then((response) => {
          //console.log(" data ==> ", response.data);
          if(helper && !response.data.statusCode) {
            let lFilterData = helper.filterData(response.data, fbNum, policyId);
            return res.json(lFilterData);
          }
          else {
            console.log("=== Inside Filter (Else) =====> ");
            return res.json(response.data);
          }
        })
        .catch( (error) => {

          if(error.response){
            console.log(" Exception while call custom ===> ", error.response.data);
            return res.send(error.response.data);
          }

        })

    })
    .catch( (error) => {
        return res.send(error);
    });

  },

}

document.js

const express = require('express');
const axios = require('axios');
const mime = require('mime-types');

const router = express.Router();
const SportsResUtility = require('../../utils/SportsResUtility');
const SprtsAppConstatnts = require('../../../constants/SprtsAppConstatnts');

const credentials = require('../../../internals/credentials.json');

const memberGroupingHelper = require('../../helpers/pcp/memberGrouping');
const exportHelper = require('../../helpers/pcp/pcpExportHelper');
const formatExportData = require('../../helpers/pcp/formatExportData');

const pcpCommonHelper = require('../../helpers/pcp/pcpCommonHelper');
const pcpProvDataHelper = require('../../helpers/group/getProvData');

//const aggregateHelper = require('../../helpers/group/aggregateFilter');

const { PcpAggregateProvidersApi } = require('psv-svc-utils');


router.get('/:searchMode/:providerSearch', (req, res, next) => {
    //  router.get('/ecmstest', (req, res, next) => {


    const { originalUrl } = req;

    //console.log(" originalUrl  ", originalUrl);

    const mode = req.params.searchMode;

    const value = encodeURIComponent(req.params.providerSearch);

    // const url = `/eerererer?mode=${mode}&value=${value}`;

    console.log("document 40--->", mode);
    console.log("for document Testing0--->", mode);





    // const url = `http://players.com/run/kit/?id=090000000009009093292390230923`;
    const url = `/tes/run/kit/?id=090000000009009093292390230923`;
    console.log("SprtsAppConstatnts.GET_JWT_TOKEN_URL--->", SprtsAppConstatnts.GET_JWT_TOKEN_URL);

    var formatUrl = SprtsAppConstatnts.DATA_DNS_NAME_CONTENT_CENTRAL + url;


    axios.get(SprtsAppConstatnts.GET_JWT_TOKEN_URL, {
        auth: {
            username: credentials.auth.racfId, password: credentials.auth.password
        }
    })
        .then((jwtResponse) => {
            console.log("jwt then----->", jwtResponse.data.jwt);
            var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
            //   var jwtToken = `Bearer jhjhjhjhjhjhererererer.eyJhcHAiOiJzdmMtcG1pbG9naW4tdGVzdCIsInN1YiI6Imk4Y3giLCJhdWQiOiJwbWlsb2dpbi10c3RhLmJjYnNmbC5jb20iLCJzcmMiOiJwbWlsb2dpbi10c3RhLmJjYnNmbC5jb20iLCJyb2xlcyI6WyJDTj1EYXRhIFNlcnZpY2VzIEVudGl0bGVtZW50cyAtIEdlbmVyYWwgLSBUZXN0LE9VPVJlcXVlc3RlZCxPVT1Hcm91cHMsREM9YmNic2ZsLERDPWNvbSIsIkNOPVByb3ZpZGVyX1NlcnZpY2VzX0VudGl0bGVtZW50cy1EZW1vZ3JhcGhpY19VcGRhdGUtVGVzdCxPVT1SZXF1ZXN0ZWQsT1U9R3JvdXBzLERDPWJjYnNmbCxEQz1jb20iLCJDTj1Qcm92aWRlcl9TZXJ2aWNlc19FbnRpdGxlbWVudHMtR2VuZXJhbF9JbnF1aXJ5LVRlc3QsT1U9UmVxdWVzdGVkLE9VPUdyb3VwcyxEQz1iY2JzZmwsREM9Y29tIiwiQ049UHJvdmlkZXJfU2VydmljZXNfRW50aXRsZW1lbnRzLU5ldHdvcmtfVXBkYXRlLVRlc3QsT1U9UmVxdWVzdGVkLE9VPUdyb3VwcyxEQz1iY2JzZmwsREM9Y29tIl0sImlzcyI6IlBNSS1UZXN0IiwiZXhwIjoxNTU5ODQ4MDcwLCJpYXQiOjE1NTk4NDYyNzAsIlNlc3Npb25JRCI6IlV1VE5yZm43c1NkNzFLcDN2enFhb2pJRUs4VT0iLCJqdGkiOiJkOGY2MTczMi01ZjQ2LTQ4NmUtOGU2NS1lMGFjMWI3NDM5YWQifQ.kscF2fkvUFkbLFQ-0JPmcZqpcJKtfn8eOR52WTBg_77KanBQ-1Qo0bfecBPXlUdfZi2PrsEw3HxlAjB9ldn1QobQMh0RfGYGq_hsV-Vi7UjFyjF4uYYsEhPGu9VdfSpFQ3HJHMYEHflgAW8PdtWzDNr6C4kzSkvZXoqgGsoMBqtLUDvTPjNgyLWWjI1xfriFOsCD_dHrM2ad22zOg3AyUReyligGbIMTUcjLUctZlHYmzsEOXIv5D-krBJqWLmdqwigPdtzuLUYvoKefkGDsd-h_Ftl4P-x__Nu0fg3tA5-rdkrDWc0QkAcWp6aECb4yNCpal6iosfQ9HxzLY1uL0A`;
            console.log('then formatUrl --->', formatUrl);

            axios.get(formatUrl, {
                headers: {
                    "Authorization": jwtToken , "Content-Type": 'application/json'

                }
            })

                .then((response) => {
                    console.log("document suceess then0--->");
                    const file = Buffer.from(response.data.content, 'base64');
                    const fileType = mime.contentType(response.data.contentInfo.fileType);
                    const fileExtension = response.data.contentInfo.fileType.toLowerCase();
                    const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
                    console.log("document suceess fileName--->", fileName);

                    //  res.set('Content-Type', fileType);
                    //res.set('Content-disposition', `attachment; ${fileName}`);
                    // res.set('Content-type', 'application/json');
                    res.send({});
                })


                .catch((e) => {
                    console.log("e catch document0--->", e);
                    console.log("e.message catch document0--->", e.message);

                    console.log("catch document--->", e.response);

                    if (e.response) {
                        return res.status(e.response.status).send(e.response.data);
                    }
                    res.status(500).send(e.message || 'Something wrong');
                });
        });


    SportsResUtility.callService(res, url);



});

module.exports = router;

日志

[nodemon] restarting due to changes...
[nodemon] starting `node node server/index.js`
controllers---> [ 'C:/codebase/erkklerlkerkl/server/controllers/root.js' ]
server is listening on 1010
  callService ===>  /eerererer/kjerjerjkjkjkjkjjkjk/userimages
  URL ===>  http://sports.com/sports/game/kjerjerjkjkjkjkjjkjk/userimages
searchMode 3---> Smart
for document Testing---> Smart
  callService ===>  /eerererer?mode=Smart&value=gr
  URL ===>  http://sports.com/sports/game?mode=Smart&value=gr
  callService ===>  /eerererer/ereererer90090990
  URL ===>  http://sports.com/sports/game/ereererer90090990
  callService ===>  /eerererer/ejkrerjkerjkerjkerjkerjk
  URL ===>  http://sports.com/sports/game/ejkrerjkerjkerjkerjkerjk
  callService ===>  /eerererer/gjgjkfjkfjkf/erjjerkjkererjkerjkjerkjerk
  URL ===>  http://sports.com/sports/game/gjgjkfjkfjkf/erjjerkjkererjkerjkjerkjerk
  callService ===>  /eerererer/fjkjdjkfjkdfjkdfjk/erjjerkjkererjkerjkjerkjerk
  URL ===>  http://sports.com/sports/game/fjkjdjkfjkdfjkdfjk/erjjerkjkererjkerjkjerkjerk
  callService ===>  /eerererer/erjjkejkerjkerjkejkerjke/erjjerkjkererjkerjkjerkjerk
  URL ===>  http://sports.com/sports/game/erjjkejkerjkerjkejkerjke/erjjerkjkererjkerjkjerkjerk
document 40---> smart
for document Testing0---> smart
SprtsAppConstatnts.GET_JWT_TOKEN_URL---> https://credentials.com
  callService ===>  /tes/run/kit/?id=090000000009009093292390230923
  URL ===>  http://sports.com/tes/run/kit/?id=090000000009009093292390230923
jwt then-----> jhjhjhjhjhjhererererer.jkjjkkjjkjkjk
then formatUrl ---> http://players.com/run/kit/?id=090000000009009093292390230923
document suceess then0--->
document suceess fileName---> filename=fdfdfdf.pdf
(node:30332) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
(node:30332) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

2 个答案:

答案 0 :(得分:0)

(node:30332) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.

此错误意味着您应要求制作了send(),然后尝试像尚未发送并再次发送一样使用它。

您将变量res传递到SportsResUtility.callService,在这里您调用res.send(),又在res.send()中调用document.js,因此您执行了两次,即不可能。

答案 1 :(得分:0)

要修复代码,我需要了解业务逻辑,这将花费太多时间来正确理解它。但是,您最容易做的就是这个

const express = require('express');
const axios = require('axios');
const mime = require('mime-types');

const router = express.Router();
const SportsResUtility = require('../../utils/SportsResUtility');
const SprtsAppConstatnts = require('../../../constants/SprtsAppConstatnts');

const credentials = require('../../../internals/credentials.json');

const memberGroupingHelper = require('../../helpers/pcp/memberGrouping');
const exportHelper = require('../../helpers/pcp/pcpExportHelper');
const formatExportData = require('../../helpers/pcp/formatExportData');

const pcpCommonHelper = require('../../helpers/pcp/pcpCommonHelper');
const pcpProvDataHelper = require('../../helpers/group/getProvData');

//const aggregateHelper = require('../../helpers/group/aggregateFilter');

const { PcpAggregateProvidersApi } = require('psv-svc-utils');


router.get('/:searchMode/:providerSearch', (req, res, next) => {
    //  router.get('/ecmstest', (req, res, next) => {


    const { originalUrl } = req;

    //console.log(" originalUrl  ", originalUrl);

    const mode = req.params.searchMode;

    const value = encodeURIComponent(req.params.providerSearch);

    // const url = `/eerererer?mode=${mode}&value=${value}`;

    console.log("document 40--->", mode);
    console.log("for document Testing0--->", mode);





    // const url = `http://players.com/run/kit/?id=090000000009009093292390230923`;
    const url = `/tes/run/kit/?id=090000000009009093292390230923`;
    console.log("SprtsAppConstatnts.GET_JWT_TOKEN_URL--->", SprtsAppConstatnts.GET_JWT_TOKEN_URL);

    var formatUrl = SprtsAppConstatnts.DATA_DNS_NAME_CONTENT_CENTRAL + url;


    axios.get(SprtsAppConstatnts.GET_JWT_TOKEN_URL, {
        auth: {
            username: credentials.auth.racfId, password: credentials.auth.password
        }
    })
        .then((jwtResponse) => {
            console.log("jwt then----->", jwtResponse.data.jwt);
            var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
            //   var jwtToken = `Bearer jhjhjhjhjhjhererererer.eyJhcHAiOiJzdmMtcG1pbG9naW4tdGVzdCIsInN1YiI6Imk4Y3giLCJhdWQiOiJwbWlsb2dpbi10c3RhLmJjYnNmbC5jb20iLCJzcmMiOiJwbWlsb2dpbi10c3RhLmJjYnNmbC5jb20iLCJyb2xlcyI6WyJDTj1EYXRhIFNlcnZpY2VzIEVudG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                headers: {
                    "Authorization": jwtToken , "Content-Type": 'application/json'

                }
            })

                .then((response) => {
                    console.log("document suceess then0--->");
                    const file = Buffer.from(response.data.content, 'base64');
                    const fileType = mime.contentType(response.data.contentInfo.fileType);
                    const fileExtension = response.data.contentInfo.fileType.toLowerCase();
                    const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
                    console.log("document suceess fileName--->", fileName);

                    //  res.set('Content-Type', fileType);
                    //res.set('Content-disposition', `attachment; ${fileName}`);
                    // res.set('Content-type', 'application/json');
                    SportsResUtility.callService(res, url);
                })


                .catch((e) => {
                    console.log("e catch document0--->", e);
                    console.log("e.message catch document0--->", e.message);

                    console.log("catch document--->", e.response);

                    if (e.response) {
                        return res.status(e.response.status).send(e.response.data);
                    }
                    res.status(500).send(e.message || 'Something wrong');
                });
        });
//     SportsResUtility.callService(res, url); remove this line, and call it higher
// instead res.send()
});

module.exports = router;