I have a simple Angular 4 app that I want to run in server side with Angular Universal (nodeJs server side rendering).
I followed these steps to configure the Angular Universal with the angular-cli help and it's all good until I try to use the angular environment.
When I try to access a property within the environment constant it works perfectly being rendered in client side (with ng serve) but in server side (ts-node src/server.ts) it throws the following error:
Error: Cannot find module 'environments/environment'
at Function.Module._resolveFilename (module.js:470:15)
at Function.Module._load (module.js:418:25)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\Dev\code-carama\src\app\auth.service.ts:3:1)
at Module._compile (module.js:571:32)
at Module.m._compile (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:385:23)
at Module._extensions..js (module.js:580:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Dev\code-carama\node_modules\ts-node\src\index.ts:388:12)
at Module.load (module.js:488:32)
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v7.10.0
npm ERR! npm v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! code-carama#0.0.0 start: `ts-node src/server.ts`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the code-carama#0.0.0 start script 'ts-node src/server.ts'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the code-carama package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! ts-node src/server.ts
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs code-carama
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls code-carama
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\dima\AppData\Roaming\npm-cache\_logs\2017-06-05T12_00_03_595Z-debug.log
This is my server.ts:
import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '#angular/platform-server';
import { enableProdMode } from '#angular/core';
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory';
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
const PORT = 4000;
enableProdMode();
const app = express();
let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();
app.engine('html', (_, options, callback) => {
const opts = { document: template, url: options.req.url };
//it serves html from the compiled angular app from the server
renderModuleFactory(AppServerModuleNgFactory, opts)
.then(html => callback(null, html));
});
app.set('view engine', 'html');
app.set('views', 'src')
app.get('*.*', express.static(join(__dirname, '..', 'dist')));
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(PORT, () => {
console.log(`listening on http://localhost:${PORT}!`);
});
And the simple service trying to access environment variables is the auth.service.ts:
import { Injectable } from '#angular/core';
import { environment } from 'environments/environment';
#Injectable()
export class AuthService {
private userManager = null;
constructor() {
console.log('AuthService instantiated in environment ' + environment.envName); //this will fail in server-side rendering
}
}
Any idea what's going with nodeJs (or angular universal) not to find that environment module?
Thanks
In projects Angular6 change 'environments/environment' by 'src/environments/environment'
Never mind, it seems the problem is that although for client side rendering the line:
import { environment } from 'environments/environment';
works well, for server side rendering the line must be:
import { environment } from '../environments/environment';
and by the way, I don't know why but by default for server-side rendering it will pick the PROD environment file.
on console: AuthService instantiated in environment prod
try to execute this commande npm run env and then execute ng serve. It's work with me
app.module.ts
Add this line:
import { environment } from '../environments/environment';
You just need to find the location of your environment.ts file.
With angular 14:
If you have your ts file here:
src\app\auth\reducers\index.ts
The answer is:
import { environment } from '../../../environments/environment';
Can you see environments folder in src folder?
And then, can you see environment.ts and environment.prod.ts on there?
If so, based on your depiction of the filesystem, you need to go back up one more level.
import { environment } from '../../environments/environment';
For me, some of build variants dev and prod were having some different const name
export const AppConfig {
instead of
export const environment {
Check that you do not have it ignored in the .gitignore
In your environment.ts add the following:
export const environment = {
production: false
};
Related
Please help:
I'm new to firebase cloud functions and face the below problem when I follow the startup guide provided by Google.
Below is the startup template index.js file
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", {structuredData: true});
response.send("Hello from Firebase!");
});
When I type firebase deploy in the terminal. It gives me these error codes:
- 1:1 error This line has a length of 85. Maximum allowed is 80 max-len
- 2:27 error Strings must use doublequote quotes
- 5:23 error Strings must use doublequote quotes
- 8:1 error Expected indentation of 0 spaces but found 1 indent
- 9:1 error Expected indentation of 0 spaces but found 1 indent
- 11:1 error Expected indentation of 0 spaces but found 1 indent
- 12:1 error Expected indentation of 2 spaces but found 3 indent
- 13:1 error Expected indentation of 2 spaces but found 3 indent
- 14:1 error Expected indentation of 0 spaces but found 1 indent
✖ 9 problems (9 errors, 0 warnings)
8 errors and 0 warnings potentially fixable with the `--fix` option.
-npm ERR! code ELIFECYCLE
-npm ERR! errno 1
-npm ERR! functions# lint: `eslint .`
-npm ERR! Exit status 1
-npm ERR!
-npm ERR! Failed at the functions# lint script.
-npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
-npm ERR! A complete log of this run can be found in:
-npm ERR! C:\Users\alant\AppData\Roaming\npm-cache\_logs\2021-06-21T13_22_47_971Z-debug.log
-events.js:292
throw er; // Unhandled 'error' event
^
-Error: spawn npm --prefix "%RESOURCE_DIR%" run lint ENOENT
at notFoundError (C:\Users\alant\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:6:26)
at verifyENOENT (C:\Users\alant\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:40:16)
at ChildProcess.cp.emit (C:\Users\alant\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:27:25)
at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12)
Emitted 'error' event on ChildProcess instance at:
at ChildProcess.cp.emit (C:\Users\alant\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\cross-env\node_modules\cross-spawn\lib\enoent.js:30:37)
at Process.ChildProcess._handle.onexit (internal/child_process.js:277:12) {
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn npm --prefix "%RESOURCE_DIR%" run lint',
path: 'npm --prefix "%RESOURCE_DIR%" run lint',
spawnargs: []
}
-Error: functions predeploy error: Command terminated with non-zero exit code1
Run this in the terminal:
eslint --fix
#Hamada
After studying the eslint documentation. I finally do this
Add this at start and at the end.
`/* eslint-disable */
//My code (all rules will be disable)
/* eslint-enable */`
Eg.
`// The Cloud Functions for Firebase SDK to
// create Cloud Functions and setup triggers.
/* eslint-disable */
const functions = require('firebase-functions');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", {structuredData: true});
response.send("Hello from Firebase!");
/* eslint-enable */
});`
I am trying to build a Nestjs api proxy (pass through). I found this package which is very simple to use: fastify-http-proxy.
The problem is I don't know how to use this package within Nestjs.
Does anybody here any experience with this, please?
import { NestFactory } from '#nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '#nestjs/platform-fastify';
import { AppModule } from './app.module';
import proxy from 'fastify-http-proxy';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({logger: true})
);
app.register(proxy, {
upstream: 'http://localhost:3000',
prefix: '/api',
http2: false
});
await app.listen(4000);
}
bootstrap();
$ npm run start
> test-api-gateway#0.0.1 start /test-api-gateway
> nest start
node_modules/fastify-http-proxy/index.d.ts:18:29 - error TS2344: Type 'RawServerBase' does not satisfy the constraint 'RouteGenericInterface'.
Type 'Server' has no properties in common with type 'RouteGenericInterface'.
18 request: FastifyRequest<RawServerBase>,
~~~~~~~~~~~~~
node_modules/fastify-http-proxy/index.d.ts:23:29 - error TS2344: Type 'RawServerBase' does not satisfy the constraint 'RouteGenericInterface'.
Type 'Server' has no properties in common with type 'RouteGenericInterface'.
23 request: FastifyRequest<RawServerBase>,
~~~~~~~~~~~~~
Found 2 error(s).
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test-api-gateway#0.0.1 start: `nest start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test-api-gateway#0.0.1 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
✘-1 ~/test-api-gateway
it works for me if using const proxy = require('fastify-http-proxy') instead import proxy from 'fastify-http-proxy'
I am writing a Node app with Typescript but my Cucumber test is in Javascript. My question: If I have a Typescript file:
import { Request, Response } from "express";
import checkCredentials from "./components/member/check-member-credentials";
import findMemberByEmail from "./components/member/find-member-by-email";
export default async (req: Request, res: Response) => {
const memberByEmail = await findMemberByEmail(req.body.password);
if (memberByEmail.error) {
return res.status(401).json({ message: "not found" });
}
const isMatch = await checkCredentials(
memberByEmail.member.password,
req.body.password,
);
if (isMatch) {
return res.status(200).json({ message: "logged in" });
}
return res.status(401).json({ message: "not auth" });
};
And I am trying to import it in the context file of Cucumber test:
require('../../../../src/controllers/login.ts');
I get the typical js error:
import { Request, Response } from "express";
^
SyntaxError: Unexpected token {
I tried to use a library typescript-require and require it before my import (as in its docs):
require('typescript-require');
const login = require("../../../../src/controllers/login.ts");
But I'm still getting error:
> NODE_ENV=development ./node_modules/.bin/cucumber-js test
src/controllers/components/member/check-member-credentials.ts(1,25): error TS2307: Cannot find module 'bcryptjs'.
src/controllers/components/member/check-member-credentials.ts(4,3): error TS2304: Cannot find name 'Promise'.
src/controllers/components/member/find-member-by-email.ts(1,16): error TS2307: Cannot find module '../../../db/models/index.js'.
src/controllers/components/member/find-member-by-email.ts(4,2): error TS2304: Cannot find name 'Promise'.
src/controllers/login-test.ts(1,35): error TS2307: Cannot find module 'express'.
src/controllers/login-test.ts(5,16): error TS1057: An async function or method must have a valid awaitable return type.
src/controllers/login-test.ts(11,25): error TS2346: Supplied parameters do not match any signature of call target.
src/controllers/login-test.ts(13,22): error TS1009: Trailing comma not allowed.
Fatal Error. Unable to compile TypeScript file. Exiting.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! my-basic-fit-v2#1.0.0 e2etest: `NODE_ENV=development ./node_modules/.bin/cucumber-js test`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the my-basic-fit-v2#1.0.0 e2etest script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/ali.atrash/.npm/_logs/2019-07-08T14_53_57_742Z-debug.log
Any other solution?
I try to create a windows installer for my elctron application but when I run the file I have this error:
spawn mono ENOENT
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! thermowell-design#1.2.0 installer-win: `npm run pack-win && node installers/windows/createinstaller.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the thermowell-design#1.2.0 installer-win script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
This is the createinstaller.js file:
const createWindowsInstaller = require('electron-winstaller').createWindowsInstaller
const path = require('path')
getInstallerConfig()
.then(createWindowsInstaller)
.catch((error) => {
console.error(error.message || error)
process.exit(1)
})
function getInstallerConfig () {
console.log('creating windows installer')
const rootPath = path.join('./')
const outPath = path.join(rootPath, 'release-builds')
return Promise.resolve({
appDirectory: path.join(outPath, 'Thermowell-Design-win32-x64/'),
authors: 'Pippo',
noMsi: true,
outputDirectory: path.join(outPath, 'windows-installer'),
exe: 'thermowell-design.exe',
setupExe: 'thermowell-design-app.exe',
setupIcon: path.join(rootPath, 'assets', 'images', 'icons', 'logo.ico')
})
}
There are the dependencie version:
electron: 5.0.0-beta.2,
electron-packager: 13.0.1,
electron-winstaller: 2.7.0
end the nodejs version is 10.15.1
It's too late to answer but leaving it for somebody if they need it in future. I got the same problem and here are my fixes:
depending upon my project structure I changed rootPath = path.join(__dirname,'../..')
install mono from https://www.mono-project.com/download/stable/#download-lin-ubuntu
install wine from https://tecadmin.net/install-wine-on-ubuntu/
The two installations are for non-windows platform if your building your installer for windows platform
Those were my fixes but here's another link that might be helpful for you.
I am facing difficulty in deploying the notification function to the firebase.
I also used npm run clean but the error showed in it that-
npm ERR! missing script: clean
The index.js code is as follows-
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification =
functions.database.ref('/Notifications/{user_id}/{notification_id}').onWrite(event => {
const user_id = event.params.user_id;
const notification = event.params.notification;
console.log('We have a notification to send to : ', user_id);
if(event.data.val()){
return console.log('A Notification has been deleted feom the database :', notification_id);
}
const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title : "Friend Request",
bosy : "You have received a new Friend Request",
icon : "default"
}
};
return admin.messaging().sendToDevice(/*Token ID*/, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
The firebase deploy error in the Command Prompt is-
C:\Users\NIHIR\Desktop\MilApp\notificationFunction>firebase deploy
=== Deploying to 'milapp2-55dfb'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint
C:\Users\NIHIR\Desktop\MilApp\notificationFunction\functions
> eslint .
C:\Users\NIHIR\Desktop\MilApp\notificationFunction\functions\index.js
19:61 error Parsing error: Unterminated template
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\NIHIR\AppData\Roaming\npm-cache\_logs\2018-03-10T22_49_06_402Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
How to fix this error?
Using it in Windows 10.
Thanks in advance.
Even after correcting the mistake, I got the error again in deploying firebase as-
C:\Users\NIHIR\Desktop\MilApp\notificationFunction\functions\index.js
33:53 error Parsing error: Unexpected token ,
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\NIHIR\AppData\Roaming\npm-cache\_logs\2018-03-11T11_27_17_307Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1
The error message is this:
19:61 error Parsing error: Unterminated template
It's referring to the fact that the template string on this line isn't terminated:
const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken).once('value');
You're missing the closing backtick for that reference string. It should be like this:
const deviceToken = admin.database().ref(`/Users/${user_id}/deviceToken`).once('value');