Угловой универсал / Экспресс: не удалось найти экспресс-просмотр - PullRequest
0 голосов
/ 11 июня 2018

Здравствуйте, я пытаюсь развернуть свое приложение, но каждый раз получаю эту ошибку:

<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>
<body>
    <pre>Error: Failed to lookup view &quot;index.html&quot; in views directory &quot;/var/www/html/dist/browser&quot;
        <br> &nbsp; &nbsp;at Function.render (/var/www/html/server.js:117552:17)
        <br> &nbsp; &nbsp;at ServerResponse.render (/var/www/html/server.js:127771:7)
        <br> &nbsp; &nbsp;at /var/www/html/server.js:141:9
        <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/var/www/html/server.js:120001:5)
        <br> &nbsp; &nbsp;at next (/var/www/html/server.js:119749:13)
        <br> &nbsp; &nbsp;at Route.dispatch (/var/www/html/server.js:119724:3)
        <br> &nbsp; &nbsp;at Layer.handle [as handle_request] (/var/www/html/server.js:120001:5)
        <br> &nbsp; &nbsp;at /var/www/html/server.js:119224:22
        <br> &nbsp; &nbsp;at param (/var/www/html/server.js:119297:14)
        <br> &nbsp; &nbsp;at param (/var/www/html/server.js:119308:14)
    

Я пытался реализовать универсальный угловой (я следовал этому: https://github.com/angular/universal-starter), но может подключить его к API.

Я думаю, что это ошибка в экспрессе, но я не могу найти что.

Сайт "вверх" по адресу:http://www.jetestmessitetranquille.ovh

Server.ts:

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import {enableProdMode} from '@angular/core';
// Express Engine
import {ngExpressEngine} from '@nguniversal/express-engine';
// Import module map for lazy loading
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';

import * as express from 'express';
import {join} from 'path';
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const http = require('http').Server(app);
const PORT = process.env.PORT || 8080;
const DIST_FOLDER = join(process.cwd(), 'dist');
const connection = mysql.createConnection({
  host: 'localhost',
  user: '****',
  password: '****',
  database: '****',
});
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.use(bodyParser.urlencoded({
    extended: true,
    limit: '5mb'
}));
app.use(bodyParser.json({ limit: '5mb' }));

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});
app.get('/product/:name', (req, res) => {
  const name = req.params.name;
  connection.query('SELECT * from product INNER JOIN image ON product.`main_image` = image.`id` WHERE slug ="' + name + '"',
      function(err, rows, fields) {
          res.json(rows);
      });
});

app.post('/sendmail', (req, res) => {
  let img;

  if (req.body.attachment != null) {
      img = req.body.attachment.split('base64,')[1];
  }

  const transporter = nodemailer.createTransport({
      host: 'SSL0.ovh.net',
      port: 465,
      secure: true, // true for 465, false for other ports
      auth: {
          user: 'jordan@serimaj.fr', // generated ethereal user
          pass: '******' // generated ethereal password
      }
  });
  // setup email data with unicode symbols
  const mailOptions = {
      from: 'jordan@serimaj.fr', // sender address
      to: req.body.email, // list of receivers
      subject: 'Demande de Devis - ' + req.body.company, // Subject line
      // bcc: 'sc@serimaj.fr',
      text: 'Copie de votre demande de contact :\nNom : ' + req.body.name + '\nMail : ' + req.body.email + '\nEntreprise : ' + req.body.company + '\nTéléphone : ' + req.body.phone + '\nMessage : ' + req.body.message, // plain text body
      attachments: [{
          filename: 'image.jpg',
          content: img,
          encoding: 'base64'
      }]
  };

  // send mail with defined transport object
  transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
          return console.log(error);
      }
      console.log('Message sent');
      res.json(info);
      transporter.close();
  });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

Любые предложения ??

[Редактировать]

Да, у меня есть сборка с:npm run build: prerender && npm run serve: prerender

Я изменяю вывод на просто / var / www / html и помещаю все мои файлы в эту папку на VPS.

Все работаетнормально на сайте, но я получаю это сообщение каждые 2/3 минуты.

Error: Failed to lookup view "index.html" in views directory ""/var/www/html"
0|server   |     at Function.render (/var/www/html/server.js:114730:17)
0|server   |     at ServerResponse.render (/var/www/html/server.js:124949:7)
0|server   |     at /var/www/html/server.js:231:9
0|server   |     at Layer.handle [as handle_request] (/var/www/html/server.js:117179:5)
0|server   |     at next (/var/www/html/server.js:116927:13)
0|server   |     at Route.dispatch (/var/www/html/server.js:116902:3)
0|server   |     at Layer.handle [as handle_request] (/var/www/html/server.js:117179:5)
0|server   |     at /var/www/html/server.js:116402:22
0|server   |     at param (/var/www/html/server.js:116475:14)
0|server   |     at param (/var/www/html/server.js:116486:14)

angular.json:

{
"$schema": "./node_modules/@angular-devkit/core/src/workspace/workspace-schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
    "ng-universal-demo": {
        "root": "",
        "projectType": "application",
        "architect": {
            "build": {
                "builder": "@angular-devkit/build-angular:browser",
                "options": {
                    "outputPath": "dist/browser",
                    "index": "src/index.html",
                    "main": "src/main.ts",
                    "tsConfig": "src/tsconfig.app.json",
                    "polyfills": "src/polyfills.ts",
                    "assets": [{
                            "glob": "**/*",
                            "input": "src/assets",
                            "output": "/assets"
                        },
                        {
                            "glob": "favicon.png",
                            "input": "src",
                            "output": "/"
                        }
                    ],
                    "styles": [
                        "src/styles.css",
                        "./node_modules/swiper/dist/css/swiper.css"
                    ],
                    "scripts": ["./node_modules/swiper/dist/js/swiper.js"]
                },
                "configurations": {
                    "production": {
                        "optimization": true,
                        "outputHashing": "all",
                        "sourceMap": false,
                        "extractCss": true,
                        "namedChunks": false,
                        "aot": true,
                        "extractLicenses": true,
                        "vendorChunk": false,
                        "buildOptimizer": true,
                        "fileReplacements": [{
                            "replace": "src/environments/environment.ts",
                            "with": "src/environments/environment.prod.ts"
                        }]
                    }
                }
            },
            "serve": {
                "builder": "@angular-devkit/build-angular:dev-server",
                "options": {
                    "browserTarget": "ng-universal-demo:build"
                },
                "configurations": {
                    "production": {
                        "browserTarget": "ng-universal-demo:build:production"
                    }
                }
            },
            "extract-i18n": {
                "builder": "@angular-devkit/build-angular:extract-i18n",
                "options": {
                    "browserTarget": "ng-universal-demo:build"
                }
            },
            "test": {
                "builder": "@angular-devkit/build-angular:karma",
                "options": {
                    "main": "src/test.ts",
                    "karmaConfig": "./karma.conf.js",
                    "polyfills": "src/polyfills.ts",
                    "tsConfig": "src/tsconfig.spec.json",
                    "scripts": [],
                    "styles": [
                        "src/styles.css"
                    ],
                    "assets": [{
                            "glob": "**/*",
                            "input": "src/assets",
                            "output": "/assets"
                        },
                        {
                            "glob": "favicon.png",
                            "input": "src",
                            "output": "/"
                        }
                    ]
                }
            },
            "lint": {
                "builder": "@angular-devkit/build-angular:tslint",
                "options": {
                    "tsConfig": [
                        "src/tsconfig.app.json"
                    ],
                    "exclude": [
                        "**/node_modules/**"
                    ]
                }
            },
            "server": {
                "builder": "@angular-devkit/build-angular:server",
                "options": {
                    "outputPath": "dist/server",
                    "main": "src/main.server.ts",
                    "tsConfig": "src/tsconfig.server.json"
                }
            }
        }
    },
    "ng-universal-demo-e2e": {
        "root": "",
        "projectType": "application",
        "cli": {},
        "schematics": {},
        "architect": {
            "e2e": {
                "builder": "@angular-devkit/build-angular:protractor",
                "options": {
                    "protractorConfig": "./protractor.conf.js",
                    "devServerTarget": "ng-universal-demo:serve"
                }
            },
            "lint": {
                "builder": "@angular-devkit/build-angular:tslint",
                "options": {
                    "tsConfig": [],
                    "exclude": [
                        "**/node_modules/**"
                    ]
                }
            }
        }
    }
},
"cli": {},
"schematics": {
    "@schematics/angular:class": {
        "spec": false
    },
    "@schematics/angular:component": {
        "spec": false,
        "inlineStyle": true,
        "inlineTemplate": true,
        "prefix": "app",
        "styleext": "css"
    },
    "@schematics/angular:directive": {
        "spec": false,
        "prefix": "app"
    },
    "@schematics/angular:guard": {
        "spec": false
    },
    "@schematics/angular:module": {
        "spec": false
    },
    "@schematics/angular:pipe": {
        "spec": false
    },
    "@schematics/angular:service": {
        "spec": false
    }
}
}
...