Angular11 using promise throwing A client-side or network error occurred: Uncaught (in promise): [object Undefined] - es6-promise

I have the following app initializer in my angular application. When deployed to test environment i am getting the following error
"A client-side or network error occurred: Uncaught (in promise): [object Undefined]"
app.module:
function initialiseApp(
appInitService: AppInitService
): () => Promise<SessionDetailsResponse> {
return async () => {
const sessionDetailsResponse: SessionDetailsResponse =
await appInitService.init();
return sessionDetailsResponse;
};
}
Here is my init service
#Injectable()
export class AppInitService {
private serviceUrl = '/v1/session';
private _http: HttpClient;
constructor(
#Inject(ENVIRONMENT) private _environment: Environment,
private sessionDetailsService: SessionDetailsService,
private httpBackend: HttpBackend
) {
this._http = new HttpClient(this.httpBackend);
}
init(): Promise<SessionDetailsResponse> {
return this._http
.get<SessionDetailsResponse>(
`${this._environment.apiBaseUrl}${this.serviceUrl}/details`
)
.toPromise()
.then((sessionDetails) => {
this.sessionDetailsService.update(sessionDetails);
return sessionDetails;
})
.catch((error) => {
handleUnauthorizedAccess(error, this._environment.baseUrl);
return Promise.reject();
});
}
}
export function handleUnauthorizedAccess(error: any, baseUrl: string) {
if (error.status === 401 && error.statusText === 'Unauthorized') {
const returnUrl = window.location.pathname;
const webUrl = `${baseUrl}/Account/Login?ReturnUrl=${encodeURIComponent(
returnUrl
)}`;
window.location.href = webUrl;
}
}

Related

getting TypeError: res.writeHead is not a functionwhen using netlify function

I get this error whenever I call the netlify function. sometimes it works and sometimes not and I get this back
Request from ::ffff:127.0.0.1: GET /.netlify/functions/getS3URL?reqType=get
Response with status 200 in 2919 ms.
C:.…AppData\Roaming\npm\node_modules\netlify-cli\node_modules\netlify-redirector\lib\redirects.js:1…
TypeError: res.writeHead is not a function
at ProxyServer. (AppData\Roaming\npm\node_modules\netlify-cli\src\utils\proxy.js:318:9)
at ProxyServer.emit (Roaming\npm\node_modules\netlify-cli\node_modules\eventemitter3\index.js:204:33)
at Socket.onOutgoingError (AppData\Roaming\npm\node_modules\netlify-cli\node_modules\http-proxy\lib\http-proxy\passes\ws-incoming.js:157:16)
at Socket.emit (node:events:525:35)
at Socket.emit (node:domain:489:12)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
api.service:
getS3URL(){
let queryParams = new HttpParams();
return this.http.get(${baseUrl}getS3URL,{ params: queryParams }).pipe();
}
In the component:
getS3URL() {
if (this.product.images[0]) {
this.api.getS3URL().subscribe({
next: (value: any) => { console.log('resp: ',value)}
, error: (err) => { console.log(‘error’, err) }
})
}
}
Netlify function:
import dotenv from ‘dotenv’
import aws from ‘aws-sdk’
import crypto from ‘crypto’
import { promisify } from “util”
import { Response } from ‘#netlify/functions/dist/function/response’
dotenv.config()
const randomBytes = promisify(crypto.randomBytes)
const region = “us-east-1”
const bucketName = “-----”
const accessKeyId = process.env[‘AWS_ACCESS_KEY_ID’]
const secretAccessKey = process.env[‘AWS_SECRET_ACCESS_KEY’]
const s3 = new aws.S3({
region,
accessKeyId,
secretAccessKey,
signatureVersion: ‘v4’
})
exports.handler = async (event: any, context: any, callback: any) => {
let resp: Response
let putURL: string = ‘’
try {
const rawBytes = await randomBytes(16)
const imageName = rawBytes.toString()
var params = { Bucket: bucketName, Key: imageName, Expires: 60 };
var promise = await s3.getSignedUrlPromise(‘putObject’, params).then(value=>putURL=value)
resp = {
statusCode: 200,
body: JSON.stringify({
URL:putURL
})
}
} catch (err: any) {
console.log(err.stack)
resp = {
statusCode: 400,
body: err.stack
};
}
return resp
}
I’m using in my project other netlify functions to do some other api requests and they are working just fine.
Used versions:
angular 14
netlify: 12.0.1
netlify-cli: 12.0.11
Thanks

Angular app initializer chrome not redirecting to login page

I am using app_initializer in my angular to check for authorization details. If unauthenticated, redirecting to login page. It works perfectly fine locally and in test environment using Firefox. But in chrome it is not redirecting to the login page. Can anyone point me if there is any issue with my below code? Thanks
Injectable()
export class AppInitService {
private serviceUrl = '/v1/session';
private _http: HttpClient;
constructor(
#Inject(ENVIRONMENT) private _environment: Environment,
private sessionDetailsService: SessionDetailsService,
private httpBackend: HttpBackend
) {
this._http = new HttpClient(this.httpBackend);
}
init(): Promise<SessionDetailsResponse | unknown> {
return this._http
.get<SessionDetailsResponse>(
`${this._environment.apiBaseUrl}${this.serviceUrl}/details`
)
.pipe(
tap((sessionDetails) => {
this.sessionDetailsService.update(sessionDetails);
return sessionDetails;
}),
catchError((error) => {
handleUnauthorizedAccess(error, this._environment.baseUrl);
return of(null);
})
)
.toPromise();
}
}
export function handleUnauthorizedAccess(error: any, baseUrl: string) {
if (error.status === 401 && error.statusText === 'Unauthorized') {
const returnUrl = window.location.pathname;
const webUrl = `${baseUrl}/Account/Login?ReturnUrl=${encodeURIComponent(
returnUrl
)}`;
window.location.href = webUrl;
}
}
app.module
{
provide: APP_INITIALIZER,
useFactory: initialiseApp,
deps: [AppInitService],
multi: true
},
function initialiseApp(appInitService: AppInitService) {
return async () => {
const sessionDetailsResponse: SessionDetailsResponse | unknown =
await appInitService.init();
return sessionDetailsResponse;
};
}

Ionic gives error undefined is not an object (evaluating '_co.user.username') when decoding the login user token

This is part of the error message that I am getting:
[Error] ERROR – TypeError: undefined is not an object (evaluating '_co.user.username') TypeError: undefined is not an object (evaluating '_co.user.username')(anonymous function)checkAndUpdateView — core.js:44...
My login process works fine and data of the user is gotten fine, on ionic serve version of my app, but on ios I can see that error message, like json encoding doesn't work fine or something. Why is the JSON working fine on website, but not on the app? Here is content of TokenService :
constructor(private cookieService: CookieService) {}
setToken(token) {
this.cookieService.set("chat_token", token);
}
getToken() {
return this.cookieService.get("chat_token");
}
deleteToken() {
this.cookieService.delete("chat_token");
}
getPayload() {
const token = this.getToken();
let payload;
if (token) {
payload = token.split(".")[1];
payload = JSON.parse(window.atob(payload));
}
return payload.data;
}
and this is the loginUser function in LoginComponent , that is triggered on logging in:
loginUser() {
this.showSpinner = true;
this.authService.loginUser(this.loginForm.value).subscribe(
data => {
this.tokenService.setToken(data.token);
localStorage.setItem("currentUser", JSON.stringify(data));
this.loginForm.reset();
setTimeout(() => {
this.router.navigate(["/streams"]);
}, 200);
},
err => {
this.showSpinner = false;
if (err.error.message) {
this.errorMessage = err.error.message;
}
}
);
}
Now, the server side, I have this rout in routes/ directory, in node express in file authRoutes.js:
router.post('/login', AuthCtrl.LoginUser);
And then I have this in routes/ directory, in file userRoutes.js:
const express = require('express');
const router = express.Router();
const UserCtrl = require('../controllers/users');
const AuthHelper = require('../Helpers/AuthHelper');
router.get('/users', AuthHelper.VerifyToken, UserCtrl.GetAllUsers);
router.get('/user/:id', AuthHelper.VerifyToken, UserCtrl.GetUser);
router.get(
'/username/:username',
AuthHelper.VerifyToken,
UserCtrl.GetUserByName
);
router.post('/user/view-profile', AuthHelper.VerifyToken, UserCtrl.ProfileView);
router.post(
'/change-password',
AuthHelper.VerifyToken,
UserCtrl.ChangePassword
);
module.exports = router;
This is the part of controller auth.js on node server side:
async LoginUser(req, res) {
if (!req.body.username || !req.body.password) {
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "No empty fields allowed" });
}
await User.findOne({ username: Helpers.firstUpper(req.body.username) })
.then(user => {
if (!user) {
return res.status(HttpStatus.NOT_FOUND).json({ message: "Username not found" });
}
return bcrypt.compare(req.body.password, user.password).then(result => {
if (!result) {
return res
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ message: "Password is incorrect" });
}
const token = jwt.sign({ data: user }, dbConfig.secret, {
expiresIn: "5h"
});
res.cookie("auth", token);
return res.status(HttpStatus.OK).json({ message: "Login successful", user, token });
});
})
.catch(err => {
console.log("Error is:");
console.log(err);
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ message: "Error occured" });
});
}
I resolved the issue by transferring all the stored data from CookieService, which is the main culprit of the error, to a localStorage. Just instead of storing payload and that cookie in CookieService, just transferred it to localStorage, and I didn't have any more problems. Seems like, the simpler - the better.

how can I do login form for angular?

I am trying to create a login form for my website. I'm using agular , express and mongoDB
Here's my controller of login function:
loginUser: (req, res) => {
User.findOne({
username: req.body.login_username
})
.then(user => {
bcrypt.compare(req.body.login_password, user.password)
.then(result => {
if (result) {
req.body.login_username = user.username
res.json({
message: "Success!",
added: true
});
} else {
console.log('Failed login attempt')
res.json({
message: "Error!",
error: err
});
}
}).catch(console.error, console.log(req.body.login_password, user.password))
})
}
and here is my login components:
userID: string;
userData: any;
loginUser: any;
error = "";
constructor(
private router: Router,
private route: ActivatedRoute,
private httpService: HttpService
) {}
ngOnInit() {
this.userID = this.route.snapshot.paramMap.get("id");
this.getSingleUser();
this.loginUser = { username: "", password: "" };
}
getSingleUser() {
let observable = this.httpService.getOneUser(this.userID);
observable.subscribe((data) => {
this.userData = data;
});
}
onSubmit() {
let observable = this.httpService.loginUser(this.loginUser);
observable.subscribe((data: any) => {
console.log("Wrong");
if (data.error) {
this.error = data.error.errors.name.message;
} else {
this.getSingleUser();
this.router.navigate([""]);
}
});
}
When I click on button my terminal getting an error like this:
undefined $2b$20$8DmOjsDm3h5q/jEq9lNauezUdFYdL6EBt9gjmCu8/0DU0kAnSSIA2
Error: data and hash arguments required
at Object.compare (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/bcrypt.js:208:17)
at /Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/promises.js:29:12
at new Promise ()
at Object.module.exports.promise (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/promises.js:20:12)
at Object.compare (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/bcrypt.js:204:25)
at /Users/nhannguyen/Desktop/personal_project/instagram/server/controllers/users.js:65:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Please add .catch(console.error) after the .then() to catch the full error.
After that check if the values are really there and if not, check if the body-parser plugin is installed

how to manipulate localStorage parameters in ionic 2 i get undefined values

i have struggles with the local storage parameter i have this //error SyntaxError at JSON.parse ()// i get " undefined" instead of the real values any help please on how to retrieve parameters from LocalStorage that i set after login in both my service auth-service.ts and auth.ts??!!
auth-service.ts
public loginChef(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
var url = 'http://localhost/PFEBACKEND/login-chef.php?
email='+credentials.email+'&passe='+credentials.password ;
this.http.get(url).map(res => res.json()).subscribe(
data=>{
let access = (data.error=== 0 )
localStorage.setItem('nom',data.nom_contact);
localStorage.setItem('nom_societe',data.nom_societe);
localStorage.setItem('email',data.email);
localStorage.setItem('telephone',data.telephone);
localStorage.setItem('matricule_fiscale',data.matricule_fiscale);
localStorage.setItem('role',data.role);
localStorage.setItem('id',data.id_chef);
this.member=data;
this.email=data.email;
this.nom=data.nom;
// this.currentUser = new User( data.nom,data.email);
observer.next(this.email,this.nom);
//observer.next(this.member);
//observer.next(access);
// console.log(this.currentUser);
observer.complete();
},
err => {
console.log(err);
observer.next(err);
},
() => console.log('service observable') );
});
}
}
offre.ts
offres: Array<any>;
loader: any;
id:string='';
constructor(public navCtrl: NavController, public navParams: NavParams,
public data:Datamembers,private auth:AuthService, public
loadingCtrl:LoadingController)
{
if(localStorage.getItem('id')){//after login i store the user data
this.id=localStorage.getItem('id');
}
}
ngOnInit()
{ var id1=parseInt(this.id).valueOf();// i get undefined value
this.presentLoading();
this.data.LoadOffres(id1).subscribe(
//function LoadOffres accept int type parameter
data => {
this.offres = data;
console.log(data);
this.loader.dismiss();
},
err => {
console.log(err);
console.log(id1);
this.loader.dismiss();
},
() => console.log('chargement terminé')
);
}
auth.ts
public loginChef() {
this.showLoading();
this.auth.loginChef(this.registerCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.email=this.auth.email;
this.nom=this.auth.nom;
this.currentUSer = this.auth.currentUser;
this.member=this.auth.member;//array
localStorage.setItem('email',this.email);
localStorage.setItem('nom',this.nom);
(....)
everything is right the problem was in my server side code