Angular httpclient 4.3 rewrite response status from 200 to 500 - httpclient

I have a server that responds with 200 status always but responds with errorCode in the body. I want to intercept that response and rewrite the status to 403 or 500. How do i do this with the new http interceptors? here is code thus far
#Injectable()
export class ApiInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(req)
.map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse && (event.body.errorCode)) {
return event.clone({status: 500})
}
});
}
}

Related

Angular 12 how to convert date object to string using http interceptor

I am trying to convert the date property to string object for all http request. Currently converting individual request body as below;
modifiedOn: modifiedOn?.map(x => moment(x).format('YYYY-MM-DD HH:mm:ss')),
But I would like this to apply for all http request in the interceptor. Can anyone help how to do this. my interceptor is as below:
#Injectable()
export class VerifyAuthorisationInterceptor implements HttpInterceptor {
constructor(#Inject(ENVIRONMENT) private environment: IEnvironment) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
map((event: HttpEvent<unknown>) => {
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401 && error.statusText === 'Unauthorized') {
const returnUrl = window.location.href;
window.location.href = radarWebUrl;
}
return throwError(error);
})
);
}
}
Add this to your intercept method before return. It will check if your request contains body and any Date elements and then converts those:
if(request?.body) {
Object.keys(request.body).forEach((key: any) => {
if(request.body[key] instanceof Date) {
request.body[key] = moment(request.body[key]).format('YYYY-MM-DD HH:mm:ss');
}
});
}

Possible Unhandled Promise Rejection (id: 0): TypeError: adapter is not a function. (In 'adapter(config)', 'adapter' is undefined)?

when i request login api the error is:
Possible Unhandled Promise Rejection (id: 0):
TypeError: adapter is not a function. (In 'adapter(config)', 'adapter' is undefined)
dispatchRequest#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:126225:19
tryCallOne#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27056:16
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:27157:27
_callTimer#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30596:17
_callImmediatesPass#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30635:17
callImmediates#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:30852:33
__callImmediates#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2736:35
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2522:34
__guard#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15
flushedQueue#http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2521:21
flushedQueue#[native code]
callFunctionReturnFlushedQueue#[native code]
running environment:
react-native#63
axios
axios config:
import axios from 'axios';
import {getAccessToken} from './util'
const service = axios.create({
baseURL: '/',
timeout: 6000
})
var token;
service.interceptors.request.use(config => {
token = getAccessToken()
if (config.headers['Content-Type']) {
console.log(config.headers['Content-Type'])
} else {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
}
config.headers['Authorization'] = `Bearer ${token}`
return config
}, error => {
return Promise.reject(error)
})
service.interceptors.response.use(response => {
return response.data
}, error => {
return Promise.reject(error)
})
export {service as axios}
request login:
const {code, message, data} = await login({phone, password})
setLoading(false)
if (code === 1) {
saveAccessToken(data.access_token)
ToastAndroid.showWithGravity(
message,
ToastAndroid.SHORT,
ToastAndroid.CENTER
)
getInfo(data.access_token)
navigation.navigate('Home');
} else {
setErrortext(message)
return
}
storage example:
const saveAccessToken = async (accessToken) => {
try {
await AsyncStorage.setItem('access_token', accessToken)
} catch (error) {
return error
}
}
error show:
when i not debugger mode and get this error, if is debugger mode running ok. i don't know where the error? please help me, thanks!
i find why the error.
i use rn-fetch-blob send http request, this package use fetch, but i use axios and ternimal tips:
Require cycle: node_modules\rn-fetch-blob\index.js -> node_modules\rn-fetch-blob\polyfill\index.js -> node_modules\rn-fetch-blob\polyfill\Blob.js -> node_modules\rn-fetch-blob\index.js
i remove this package and send http request is ok!

Getting 204 response before db action callback in expressjs, mongodb, inversifyjs

I want to add new document to the mongodb and get an inserted id as response with 201 status, but when db.insertOne called I get response with 204 status code before tap works. Here is my controller
#controller('/stars')
export class StarController {
constructor(#inject(TYPES.StarService) private starService: IStarService) {}
#httpPost('/')
public newStar(request: Request, response: Response) {
this.starService.insert(request.body)
.pipe(
tap(result => response.status(201).json(result))
).subscribe();
}
}
In my StarService
#injectable()
export class StarService implements IStarService {
private mongoClient: MongoDBClient;
constructor(#inject(TYPES.MongoDBClient) mongoClient: MongoDBClient) {
this.mongoClient = mongoClient;
}
public insert(star) {
return this.mongoClient.insertOne(star, 'stars');
}
In MongoDBClient
public insertOne<T>(document: T, collectionName: string): Observable<ObjectID> {
return from(
this.db.collection(collectionName).insertOne(document))
.pipe(
map(
(result: InsertOneWriteOpResult) => {
return result.insertedId;
}));
}
How can I get json response with correct status code and body

Am I using Angular 5 http interceptor correctly?

I always return http 200 back and define my own error code. If using Promise, I could reject a response which contains customized error. How can I do it using Observable? I do it like this and it works, but is it a correct way?
My interceptor:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).flatMap((event: any) => {
if (event instanceof HttpResponse) {
if (event.body.status) {
if (event.body.status === 'NOK') {
return Observable.throw(event.body);
}
}
}
return Observable.create(observer => observer.next(event));
})}
My provider:
private handleErrorObservable(error: Response | any) {
return Observable.throw(error.message || error);
}
constructor(public http: HttpClient) {
}
signIn(params: any) {
...(some more codes here)
return this.http.post(this.apiUrl + func, requestData, options).map(
(response) => {
//do something with the response
return response;
}).catch(this.handleErrorObservable);
}
My component:
if (form.valid) {
this.auth.signIn(this.login).subscribe(val => {
//console.log(val);
this.navCtrl.setRoot('WebPage');
}, err => {
// error handling here
})
}

Angular2 Http / Jsonp Not Making Request

I'm using Angular 2.0.0-beta.16 and attempting to get data from my RESTful API. I have the following service:
import {Injectable} from 'angular2/core';
import {Jsonp, Response, Headers, RequestOptions} from 'angular2/http';
import {Store} from './store';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';
#Injectable()
export class StoreService {
constructor(private jsonp: Jsonp) {
}
getStores(): Observable<Store[]> {
console.log("getting stores");
// let headers = new Headers({ 'Content-Type': 'application/json' });
// let options = new RequestOptions({ headers: headers });
return this.jsonp.get("http://localhost:8080/stores")
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
console.log(res.status);
if (res.status < 200 || res.status >= 300) {
throw new Error('Bad response status: ' + res.status);
}
let body = res.json();
return body.data || {};
}
private handleError(error: any) {
// In a real world app, we might send the error to remote logging infrastructure
let errMsg = error.message || 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
From my component, I'm calling getStores(). I know it is getting into the getStores() function because I am getting the console.log message. However, nothing else happens. No request is being made that I can see in the chrome dev tools. No errors being logged to the console. Just nothing. I've tried both Jsonp and Http but they both give the same results.
You need to subscribe to the observable returned by getStores(). Observables are lazy and don't do anything without subscribe() or `toPromise()
getStores().subscribe(val => { console.log(val); };