-1
I’m having trouble with ionic 4
and angular
to make a request post
in case I am implementing the login, but is not being sent my body
in the request.
My files are like this:
Baserequest.
public post(data): Observable<any> {
let dataString = JSON.stringify(data);
return this.http.request('POST', this.url, {
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: dataString,
observe: 'body',
responseType: 'json'
}).catch(this.errorHandler);
}
Interceptor.ts
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { LoadingController } from '@ionic/angular';
@Injectable()
export class HttpInterceptorsService implements HttpInterceptor {
loaderToShow: any;
constructor(
public loadingController: LoadingController
) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.showLoader();
const token = "";
//Authentication by setting header with token value
if (token) {
request = request.clone({
setHeaders: {
'Authorization': token
}
});
}
if (!request.headers.has('Content-Type')) {
request = request.clone({
setHeaders: {
'content-type': 'application/json'
}
});
}
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
return next.handle(request).catch((err: any) => {
if (err.status === 401) {
console.error('error in http-interceptor', err.status);
}
this.hideLoader();
return next.handle(request);
});
}
async showLoader() {
this.loaderToShow = await this.loadingController.create({
message: 'Processing Server Request'
})
return await this.loaderToShow.present();
}
hideLoader() {
setTimeout(() => {
console.log(this.loadingController)
this.loaderToShow.dismiss();
}, 1000)
}
}
In google emulating Chrome the result is:
In my API I receive as follows:
async function apiLogin(rawreq: Request, rawres: Response) {
let req = rawreq as NGORequest
let res = rawres as NGOResponse
let loginparts = req.body.username.split('@');
let username = loginparts.length == 2 ? loginparts[0] : loginparts[0];
let domain = loginparts.length == 2 ? loginparts[1] : 'ngo';
let password = req.body.password;
let db = await NGOServiceLocator.getDb(domain)
let user = await db.collection("users").findOne({ login: username });
}
And to receive the requisition I do so:
me.server.use("/api/login", apiLogin)
The server startup and configuration is like this:
function initExpress() {
me.server.get("/ping", (req, res) => {
res.json(1).end();
});
me.server.use(upgradeReqAndRes);
let secmw = createSecurity(me);
me.server.use(compression({ filter: shouldCompress }))
function shouldCompress(req: Request, res: Response) {
if (req.headers['x-no-compression']) {
return false
}
// fallback to standard filter function
return compression.filter(req, res)
}
me.server.use(secmw);
// me.server.use(express.static('webroot'));
me.server.use(NGOStaticResolve);
me.server.use(logAndTimeMW);
me.server.use(cookieparser());
me.server.use(bodyparser.json({ limit: '150mb' }));
me.server.use(bodyparser.urlencoded({
limit: '150mb',
extended: true
}));
me.server.use(NGOUploadMW);
me.server.use(requestQuery.parseQuery);
me.httpServer = createServer();
me.httpServer.on('request', me.server);
mongoose.set('debug', function (col: any, method: any, query: any, doc: any, opts: any) {
NGOLog.trace(`${col}.${method}(${JSON.stringify(query)})=>${JSON.stringify(doc)}`)
});
}
After some time waiting for the request to complete I received this error in the console.log
core.js:9110 ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:6100/api/login","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:6100/api/login: 0 Unknown Error","error":{"isTrusted":true}}
at resolvePromise (zone-evergreen.js:797)
at zone-evergreen.js:707
at rejected (tslib.es6.js:71)
at ZoneDelegate.invoke (zone-evergreen.js:359)
at Object.onInvoke (core.js:34201)
at ZoneDelegate.invoke (zone-evergreen.js:358)
at Zone.run (zone-evergreen.js:124)
at zone-evergreen.js:855
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
What has been my mistake, I’m missing in CORS
, I don’t know why you’re not sending the body.
The "provisional headers Shown" indicates that the request has not ended or you will receive some connection or Cors error below. PS: put the result of
let dataString = JSON.stringify(data)
in aconsole.log(dataString);
– Guilherme Nascimento
The result was this from the console.log {"username":"[email protected]","password":"Toor"}
– Renan Rodrigues
The "provisional headers Shown" indicates that the request has not ended or you will receive some connection or Cors error below. Received an error in the console?
– Guilherme Nascimento
No, the request is compelled, but the error occurs on the line that has Let loginparts = req.body.username.split('@'); because it cannot find req.body.
– Renan Rodrigues
@Guilhermenascimento I updated my question, now had an api error return
– Renan Rodrigues
That’s exactly what I said in the first comment, "a Cors error", if you don’t set up Cors in Express to allow another domain the security will bar, it’s simple and you’re done: https://expressjs.com/en/resources/middleware/cors.html
– Guilherme Nascimento