Невозможно отобразить страницу, поскольку произошла внутренняя ошибка сервера. Node.js azure - PullRequest
0 голосов
/ 11 января 2020

У меня есть node.js приложение, оно работает локально, когда я развернул его в Azure Служба приложений. Появляется ниже ошибка:

Страница не может быть отображена, поскольку произошла внутренняя ошибка сервера.

ниже мой сервер. js код:

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const errorhandler = require("errorhandler");
const morgan = require("morgan");
const cors = require("cors");
const router_1 = require("./routes/router");
const bunyan_logger_1 = require("./lib/loggers/bunyan.logger");
require("reflect-metadata");
//const database = require('./data/dbprovider/dbmssql');
class Server {
    constructor() {
        this.port = process.env.PORT || 3000;
        this.logger = new bunyan_logger_1.bunyanLogger();
        this.app = express();
        this.initExpressMiddleWare();
        this.initCustomMiddleware();
        this.initRoutes();
        this.start();
    }
    start() {
        this.app.listen(this.port, (err) => {
            if (err) {
                this.logger.StartLogger().error('In Server.TS start see details: ' + err);
            }
            else {
                console.log('Listening on http://localhost:%d', process.env.NODE_ENV, this.port);
            }
        });
    }
    initExpressMiddleWare() {
        this.app.use(express.static(__dirname + '/public'));
        this.app.use(morgan('dev'));
        this.app.use(bodyParser.urlencoded({ extended: true }));
        this.app.use(bodyParser.json());
        this.app.use(errorhandler());
        this.app.use(cookieParser());
        this.app.use(cors());
        // Add headers
        this.app.use(function (req, res, next) {
            // Website you wish to allow to connect
            const allowOrigin = ['https://senserver4.azurewebsites.net','http://localhost:3000'];
            const origin = req.headers.origin;
            if (allowOrigin.indexOf(origin) > -1) {
                res.setHeader('Access-Control-Allow-Origin', origin);
            }
            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
            // Set to true if you need the website to include cookies in the requests sent
            // to the API (e.g. in case you use sessions)
            res.setHeader('Access-Control-Allow-Credentials', true);
            // Pass to next layer of middleware
            next();
        });
        //this.app.use(csrf({ cookie: true }));
        // this.app.use((req: { csrfToken: () => void; }, res: { locals: { _csrf: any; }; cookie: (arg0: string, arg1: any) => void; }, next: () => void) => {
        //     let csrfToken = req.csrfToken();
        //     res.locals._csrf = csrfToken;
        //     res.cookie('XSRF-TOKEN', csrfToken);
        //     next();
        // });
        process.on('uncaughtException', (err) => {
            if (err)
                console.log(err, err.stack);
        });
    }
    initCustomMiddleware() {
        if (process.platform === "win32") {
            require("readline").createInterface({
                input: process.stdin,
                output: process.stdout
            }).on("SIGINT", () => {
                process.exit(1);
            });
        }
        process.on('SIGINT', () => {
            process.exit(1);
        });
    }
    initRoutes() {
        (new router_1.Router()).load(this.app, './controllers');
    }
}
let server = new Server();
//# sourceMappingURL=server.js.map

Я создал файл web.config в root моего проекта, ниже приведен код web.config:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
<appSettings>

</appSettings>
<system.webServer>
<staticContent>
  <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
</staticContent>

<modules runAllManagedModulesForAllRequests="false" />

<iisnode watchedFiles="web.config;*.js;routes\*.js;views\*.pug"/>

<handlers>
  <add name="iisnode" path="app.js" verb="*" modules="iisnode" />

</handlers>

<security>
  <requestFiltering>
    <hiddenSegments>
      <remove segment="bin" />
    </hiddenSegments>
  </requestFiltering>
</security>

<rewrite>
  <rules>
    <clear />

    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="^server.js\/debug[\/]?" />
    </rule>

    <rule name="app" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="iisnode.+" negate="true" />
      <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
      <action type="Rewrite" url="app.js" />
    </rule>
  </rules>
</rewrite>
</system.webServer>

Я добавил свой сервер. js в сопоставлении путей, но не смог решить проблему.

Ошибка при получении в консоли:

Tue Jan 14 2020 16:01:06 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\public\data\repos\Agent.repo.js:13
async getAllAgent() {
      ^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\home\site\wwwroot\public\controllers\api\agents\agent.controller.js:3:22)
at Module._compile (module.js:570:32)     

1 Ответ

0 голосов
/ 14 января 2020

Эта ошибка является общим описанием ошибки IIS server 500. Найти причину вопроса root будет трудно только по общему описанию.

Пожалуйста, попробуйте нижеприведенный код web.config, чтобы показать подробности, которые могут вам помочь, и не комментируйте предыдущий код .

<configuration>
    <system.webServer>
        <httpErrors errorMode="Detailed" />
        <asp scriptErrorSentToBrowser="true"/>
    </system.webServer>
    <system.web>
        <customErrors mode="Off"/>
        <compilation debug="true"/>
    </system.web>
</configuration>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...