Basically the router.beforeEach() method is doing something I don't understand.
I get the jist of the issue being that when my route is re-directing to /login it will do it around 960 times or so until the error occurs.
my code is like so:
Router:
let router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path:'/login',
name: 'login',
component: Login,
meta: {
requiresAuth: 'false'
}
},
{
path:'/register',
name: 'register',
component: Register,
meta: {
requiresAuth: 'false'
}
},
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: 'True'
}
}
]
})
the beforeEach() method
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
console.log(to.matched.some(record => record.meta.requiresAuth))
if (localStorage.getItem('jwt') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
} else {
next()
}
} else {
if (localStorage.getItem('jwt') != null) {
next({
path: '/',
params: { nextUrl: '/' }
})
} else {
next()
}
}
})
I've looked through countless threads and other places and none have the same issue as me (or I'm overlooking things). Anyone got an idea on how to fix, and what is actually happening to make the error occur in this? from what I can tell I have nothing named twice or any other function/component fire off when it shouldn't.
Fixed it. I'm a bit special in the head. For anyone with the same issue just change the routes to
routes: [
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false
}
},
{
path:'/register',
name: 'register',
component: Register,
meta: {
requiresAuth: false
}
},
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: true
}
}
]
For anyone who gets this error without any obvious mistake, try deleting node_modules and running npm install again.
I got this error when switching git branches and the only thing that changes were the packages, so I tried the above and it got rid of the problem :)
Related
I want to use handle bars template in my nest js application:
<!--confirmation.hbs-->
<p>Hello template</p>
This file is located in src/mail/templates/confirmation.hbs. Also i try to send this template as email:
//mail service
#Injectable()
export class EmailService {
constructor(private readonly mailerService: MailerService) {}
public example(): void {
this.mailerService
.sendMail({
to: 'mail', // list of receivers
from: 'test#nestjs.com', // sender address
subject: 'Testing Nest MailerModule ✔', // Subject line
template: './confirmation',
})
.then((r) => {
console.log(r, 'email is sent');
})
.catch((e) => {
console.log(e, 'error sending email');
});
}
}
My app.module.ts looks:
#Module({
imports: [
MailerModule.forRoot({
transport: {
service: 'Gmail',
auth: {
user: '---secret',
pass: '---secret',
},
},
defaults: {
from: '"No Reply" <no-reply#localhost>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5433,
username: '-',
password: '-',
database: '-',
entities: [RegisterEntity],
synchronize: true,
}),
AuthenticationModule,
],
controllers: [AppController, AuthenticationController],
providers: [AppService, AuthenticationService],
})
This is my main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix(CONSTANTS.GLOBAL_PREFIX);
await app.listen(3000);
}
bootstrap();
This is my nest-cli.hbs
{
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
"mail/templates/**/*.hbs"
],
"watchAssets": true
}
}
The email is sent if don't send a template, so the code is working. Trying to send an email template like is my code above i get this error: TypeError: Cannot destructure property 'templateName' of 'precompile(...)' as it is undefined. Question: Why i get this issue and how to get rid of it?
Your files are located inside src/mail/templates/.
But in your module you have dir: __dirname + '/templates',.
Here __dirname returns app.module.ts folder location path which is src/.
change
dir: __dirname + '/templates',
to
dir: __dirname + '/mail/templates',
Since this bug is not yet released #743 (to this date), I rolled back to previous version:
npm i --save #nestjs-modules/mailer#1.6.0 --force
For me,this is a template file path issue.
Review your template.dir in your MailerModule config, and compare it to your project "dist" directory.
if your template file path is "dist/templates/template.hbs"
then your template.dir should be ${process.cwd()}/templates
else if your dist directory is "dist/src/templates/template.hbs" ,which is depend on your compile configs.
then your template.dir config should be join(__dirname, 'templates')
I am trying to use an exception filter in my NestJS app. I have to translate my exception message into another language based on the request value. I have two languages file en and fr.
I have initialized i18N in my app.module.ts as per the following:
#Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
parser: I18nJsonParser,
parserOptions: {
path: path.join(__dirname, '/i18n/'),
},
resolvers: [
PathResolver,
{ use: QueryResolver, options: ['lang', 'locale', 'l'] },
AcceptLanguageResolver
]
}),
],
controllers: [AppController],
providers: [AppService,
{
provide: APP_FILTER,
useClass: NotFoundExceptionFilter,
},
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
}
],
})
export class AppModule { }
My Exception filter class looks like this:
#Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
constructor(private readonly i18n: I18nService) { }
async catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest();
const statusCode = exception.getStatus();
await this.i18n.translate('message.Unauthorized', { lang: 'fr' }).then(message => {
console.log('message -> ', message);
response.status(403).send({
status: 6,
message: message,
data: null
});
})
}
}
I am throwing an exception from the LocalAuthGuard file:
#Injectable()
export class LocalAuthGuard implements CanActivate {
canActivate(context: ExecutionContext,): boolean | Promise<boolean> | Observable<boolean> {
const request = context.switchToHttp().getRequest().body;
if(isEmpty(request.authkey)){
return false;
}else{
return true;
}
}
}
I have just put here my sample code from the project. When I run this project by some specific URL, I am not getting messages in the specific language. I am getting the following output in my console log.
message -> message.Unauthorized
It should return the message in fr language.
Can anybody help me, where am I going wrong?
I forgot to add the path in nest-cli.json. If we put the path in that file as below then the above code perfectly works fine.
{
"collection": "#nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": ["i18n/**/*","ssl/**/*"]
}
}
I'm using NestJs Mailer Module, the latest stable version. You can find the documentation here.
I've search a solution for this error but I found nothing:
Error: self signed certificate in certificate chain
app.module.ts:
#Module({
imports: [
MailerModule.forRoot({
transport: 'smtps://user#domain.com:pass#smtp.domain.com',
defaults: {
from:'"nest-modules" <modules#nestjs.com>',
},
template: {
dir: __dirname + '/templates',
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
}),
],
})
export class AppModule {}
sending the email:
this.mailerService.sendMail({
to: 'example#domain.com',
subject: 'subject'
text: 'blahblahblah'
html: 'blahblahblah'
}).then(() => {
this.logger.log('Error email sent!', 'HttpExceptionFilter');
}).catch(err => {
this.logger.error('Error while sending error email.', err, 'HttpExceptionFilter');
});
As a solution, you can use tls: { rejectUnauthorized: false } in your transport options.
I'm Working with MEAN Stack , And i have 3 layouts and i want to protect every layout routes to prevent other layouts to access it
const routes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full'
},
{
path: 'main-admin',
component: MainAdminLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/main-admin-layout/main-admin-layout.module').then(m => m.MainAdminLayoutModule)
}
]
},
{
path: 'main-admin',
component: MainAdminLayoutComponent,
loadChildren: () =>
import('./main-admin-components/main-admin.component.module').then(m => m.MainAdminComponentModule)
},
{
path: '',
component: AdminLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/admin-layout/admin-layout.module').then(m => m.AdminLayoutModule)
}
]
},
{
path: '',
component: AdminLayoutComponent,
loadChildren: () =>
import('./components/component.module').then(m => m.ComponentModule)
},
{
path: 'user',
component: SiteLayoutComponent,
children: [
{
path: '',
loadChildren: () =>
import('./layouts/site-layout/site-layout.module').then(m => m.SiteLayoutModule)
}
]
},
{
path: '',
component: UserLayoutComponent,
children: [
{
path: 'account',
loadChildren: () =>
import('./layouts/user-layout/user-layout.module').then(m => m.UserLayoutModule)
}
]
},
{
path: '**',
component: NotFoundComponent
}
];
Each route i want to protect ... Let's say i just a user and if i want to access admin routes redirect me to my dashboard
Any help please ??!!
The thing that you are trying to achieve over here is, users will have access to visit only particular components. In case if they are trying to visit a component for which they are not having access, they must be redirected to some other component.
This can be achieved by a feature called Angular Route Resolvers;. Usiing which you will run a piece of code before navigating ot that component and decide whether it can be navigated or not. You can find a detail implementation of route resolvers with example over here - https://dzone.com/articles/understanding-angular-route-resolvers-by-example
I am working on angular 6 .. I want to make the user redirects to specific route from outer link .. but when the user clicks the link he got redirected to "index"
and this is my routes
RouterModule.forRoot([
{ path: "Startup", component: StartupComponent },
{ path: "Login", component: SigninComponent },
{ path: "FirstPage", component: FirstPageComponent },
{ path: "Index", component: IndexComponent, canActivate: [ComponentGuardService] },
{ path: "Requests", component: IndexComponent, canActivate: [ComponentGuardService] },
{ path: "RequestsDetails/:id", component: RequestsDetailsComponent, canActivate: [ComponentGuardService] },
{ path: "RequestsStatistics", component: RequestsStatisticsComponent, canActivate: [AdminGuardService,ComponentGuardService] },
{ path: "", redirectTo: "Index", pathMatch: "full" },
{ path: "**", redirectTo: "Login", pathMatch: "full" }
], { useHash: true })
and ComponentGuardService
canActivate(): boolean {
let me = Shared.Me;
if (me == null || me.Id == "") {
this.navigator.navigate(["/Startup"]);
return false;
}
else
return true;
}
I want to make the user redirect to Requests route
thank you :)