ошибка сервера js узла, но не указывает на какой-либо конкретный файл - PullRequest
0 голосов
/ 09 июня 2019
  • У меня есть один api один домен и все остальные apis в другом домене.
  • , поэтому в SprtsAppConstatnts.js я жестко закодировал все домены.
  • при печатиformatUrl ---> который присутствует в document.js, он печатает, который является правильным доменом, затем formatUrl ---> http://players.com/run/kit/?id=090000000009009093292390230923
  • , где он присутствует в URL ===> в файле SportsResUtility.jsпечатает неверный URL домена ===> http://sports.com/tes/run/kit/?id=090000000009009093292390230923
  • , поскольку он берет жестко закодированное значение exports.DATA_DNS_NAME = "http://sports.com"; из файла SprtsAppConstatnts.js
  • , не зная, как добавить кодировку в 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 голосов
/ 09 июня 2019

Чтобы исправить код, мне нужно знать бизнес-логику, чтобы понять ее, потребуется слишком много времени.Но самое простое, что вы можете сделать, это

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');
                    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;
0 голосов
/ 09 июня 2019

(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, так что вы делаете это дважды, что невозможно.

...