angular / universal

Server-side rendering and Prerendering for Angular
MIT License
4.04k stars 484 forks source link

Av9 AWS Lightsail Deployment: "Error: Cannot find module /home/bitnami/projectName/node_modules/zone.js/dist/zone-node" #1528

Closed Nephera closed 4 years ago

Nephera commented 4 years ago

🐞 Bug report

Command (mark with an x)

Is this a regression?

Yes, the previous version in which this bug was not present was: Angular v7 ### Description A clear and concise description of the problem... This command works perfectly fine on my machine, but upon deployment to my AWS Lightsail instance (dragged the dist folder over), I am greeted with the following error code when running "sudo node server.ts": "SyntaxError: Cannot use import statement outside a module". I found this [link](https://github.com/TypeStrong/ts-node/issues/922) which prompted me to add "type": "module" to my package.json. Now I am getting the following error: "Error: Cannot find module /home/bitnami/projectName/node_modules/zone.js/dist/zone-node". All of the other threads I was able to find on this error are related to Vue and not Angular, so I decided to post this issue here specifically. This is using the standard server.ts file (with slight modifications supporting some api routes) that was provided with Angular 9 Universal which I got through Angular-CLI in VS Code. ``` import 'zone.js/dist/zone-node'; // <-- ERROR HERE import { ngExpressEngine } from '@nguniversal/express-engine'; import * as express from 'express'; import { join } from 'path'; import { AppServerModule } from './src/main.server'; import { APP_BASE_HREF } from '@angular/common'; import { existsSync } from 'fs'; import { request } from 'http'; const mongoose = require('mongoose'); const moment = require('moment'); const someRoutes = require('./src/backend/routes/someroutes'); const otherRoutes = require('./src/backend/routes/otherroutes'); ... const production = false; mongoose.set('useUnifiedTopology', true); if(production){ mongoose.connect("mongodb://user:password@XXX.XXX.XXX.XXX:XXXXX/X", { useNewUrlParser: true, useCreateIndex: true }) .then(() => {console.log('[P] Connected to MongoDB at XXX (localhost:27017)');}) .catch(() => {console.log('[P] Failed connection to MongoDB at XXX (localhost:27017)');}); } else{ mongoose.connect('mongodb://user:password@XXX.XXX.XXX.XXX:XXXXX/X', { useNewUrlParser: true, useCreateIndex: true }) .then(() => {console.log('[D] Connected to MongoDB at XXX);}) .catch(err => {console.log('[D] Failed connection to MongoDB at XXX: ' + err);}); } // The Express app is exported so that it can be used by serverless Functions. export function app() { const server = express(); const distFolder = join(process.cwd(), 'dist/projectName/browser'); const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'; server.use((req, res, next) => { console.log("[" + moment().utc().format('hh:mm:ss') + "] Client Connected: " + req.ip + " " + req.method + ": " + req.path); res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS"); next(); }); // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine) server.engine('html', ngExpressEngine({ bootstrap: AppServerModule, })); server.set('view engine', 'html'); server.set('views', distFolder); server.use("/api/someRoutes", someRoutes); server.use("/api/otherRoutes", otherRoutes); ... // Any other api endpoints that aren't supported by above routes server.get('/api/*', (req, res) => { console.log(res); res.status(404).send('data requests are not supported'); }); // Base route uses the Universal engine server.get('/', (req, res) => { res.render('index', { req: req, res: res, preboot: true }); }); // Serve static files from /browser server.get('*.*', express.static(distFolder, {maxAge: '1y'}), (req, res) => { }); // All regular routes use the Universal engine server.get('*', (req, res) => { res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] }); }); return server; } function run() { const port = process.env.PORT || 4000; // Start up the Node server const server = app(); server.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } // Webpack will replace 'require' with '__webpack_require__' // '__non_webpack_require__' is a proxy to Node 'require' // The below code is to ensure that the server is run only when not requiring the bundle. declare const __non_webpack_require__: NodeRequire; const mainModule = __non_webpack_require__.main; const moduleFilename = mainModule && mainModule.filename || ''; if (moduleFilename === __filename || moduleFilename.includes('iisnode')) { run(); } export * from './src/main.server'; ``` I've been trying for about a month now to implement SSR in my free time and being so close to the finish line has me pulling my hair out. ## πŸ”¬ Minimal Reproduction

πŸ”₯ Exception or Error





bitnami@ip-XXX-XXX-XXX-XXX:~/projectName$ sudo node server.ts
(node:25297) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.ts:61
  let url = moduleWrapResolve(specifier, parentURL);
            ^

Error: Cannot find module /home/bitnami/projectName/node_modules/zone.js/dist/zone-node imported from /home/bitnami/projectName/server.ts
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
    at Loader.resolve (internal/modules/esm/loader.js:85:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:191:28)
    at ModuleWrap. (internal/modules/esm/module_job.js:42:40)
    at link (internal/modules/esm/module_job.js:41:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

🌍 Your Environment





The program 'ng' is currently not installed. You can install it by typing:
sudo apt install ng-common

After using sudo apt install ng-common, I'm taken to a screen that displays the following.  Looks like VIM is open, but it's not VIM.  Maybe another text editor I'm not familiar with:

-----Mg: version                          (fundamental)----All------------------
(New file)

Anything else relevant?

This is utilizing AWS Lightsail's MEAN Stack which utilizes Apache to negotiate between the client and the node server(s). The stack is made by Bitnami and originally used Node 8, which I've since manually upgraded to Node 12.

Nephera commented 4 years ago

Well, I did a dumb and tried running a barebones server.ts on my AWS instance, I should have run the main.js file that was created during the npm run build:ssr script. If anyone runs into this error in the future, this is likely the issue. I have some other things to sort out now, but I feel like I'm on the cusp of getting this to work.

angular-automatic-lock-bot[bot] commented 4 years ago

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.