Home > Net >  why the Api is giving error with 403 in angular
why the Api is giving error with 403 in angular

Time:10-21

I am calling get api in angular component But in console it is giving error 403 but the same api is giving correct response when i send it from the postman. I guess there is some issue with my angular code.

postman response

enter image description here

upload.component.ts

import { Component, OnInit } from '@angular/core'
import { UploadService } from 'src/app/services/upload.service'
import { AuthService } from 'src/app/services/auth.service'
import { HttpClient,HttpHeaders} from '@angular/common/http';
import {
    FormBuilder,
    FormGroup,
    Validators,
    AbstractControl,
    FormArray,
} from '@angular/forms'


@Component({
    selector: 'app-upload',
    templateUrl: './upload.component.html',
    styleUrls: ['./upload.component.css'],
})
export class UploadComponent implements OnInit {
    uploadForm: FormGroup
    hasError: boolean
    error
    fileToUpload: File = null
    tags = []
    selectedTags = []
    artefactTags = []
    showMessage: boolean
    message: string;
    refHtml = [];
    internalRef = [];
    externalRef = [];
    InstancesList: {};
    constructor(
        private fb: FormBuilder,
        private uploadService: UploadService,
        private authService: AuthService,
        private http:HttpClient,
    ) {
        this.uploadForm = fb.group({
            title: ['', [this.checkboxSpace]],
            provider: ['', [this.checkboxSpace]],
            type: ['', [this.checkboxSpace]],
            fileType: ['', [this.checkboxSpace]],
            description: ['', [this.checkboxSpace, Validators.maxLength(500)]],
            howToUse: ['', [this.checkboxSpace, Validators.maxLength(500)]],
            tags: ['', [Validators.required, Validators.maxLength(7)]],
            licenseDate: ['', ''],
            licenseNo: ['', ''],
            file: ['', [Validators.required]],
            artefact: [''],
            refClassification: ['', ''],
            refLink: ['', ''],
        
        })
      

        this.tags = [
            { title: 'science', value: 0 },
            { title: 'data', value: 1 },
            { title: 'computer', value: 2 },
            { title: 'health', value: 3 },
            { title: 'internet software', value: 4 },
            { title: 'computing', value: 5 },
            { title: 'natural and physical sciences', value: 6 },
            { title: 'internet', value: 7 },
            { title: 'web services', value: 8 },
            { title: 'crime', value: 9 },
            { title: 'finance', value: 10 },
            { title: 'machine learning', value: 11 },
            { title: 'credit card', value: 12 },
            { title: 'Computer science', value: 13 },
            { title: 'biology', value: 14 },
            { title: 'Starter code', value: 15 },
            { title: 'beginner', value: 16 },
            { title: 'geospatial analysis', value: 17 },
            { title: 'data visualisation', value: 18 },
            { title: 'Exploratory Data Analysis', value: 19 },
            { title: 'eda', value: 20 },
            { title: 'deep learning', value: 21 },
            { title: 'tutorial', value: 22 },
            { title: 'classification', value: 23 },
            { title: 'video data', value: 24 },
            { title: 'text data', value: 25 },
            { title: 'data cleaning', value: 26 },
            { title: 'regression analysis', value: 27 },
            { title: 'ensembling', value: 28 },
            { title: 'xgboost', value: 29 },
            { title: 'feature engineering', value: 30 },
            { title: 'model comparison', value: 31 },
            { title: 'nlp', value: 32 },
            { title: 'deep learning', value: 33 },
            { title: 'learn', value: 34 },
            { title: 'pre-processing', value: 35 },
            { title: 'banking', value: 36 },
            { title: 'linear regression', value: 37 },
            { title: 'pandas profiling', value: 38 },
            { title: 'univariate analysis', value: 39 },
            { title: 'bivariate analysis', value: 40 },
            { title: 'data profiling', value: 41 },
            { title: 'missing value imputation', value: 42 },
            { title: 'outlier detection', value: 43 },
            { title: 'multivariate analysis', value: 44 },
            { title: 'credit data', value: 45 },
            { title: 'default payments', value: 46 },
            { title: 'customer churn', value: 47 },
            { title: 'statistics', value: 48 },
            { title: 'banking data', value: 49 },
            { title: 'fraud detection', value: 50 },
            { title: 'transaction', value: 51 },
            { title: 'fraudulent transaction', value: 52 },
            { title: 'credit risk', value: 53 },
            { title: 'marketing campaign', value: 54 },
            { title: 'bank', value: 55 },
            { title: 'product', value: 56 },
            { title: 'loan', value: 57 },
            { title: 'car loan', value: 58 },
            { title: 'loan status', value: 59 },
            { title: 'loan data', value: 60 },
            { title: 'credit history', value: 61 },
            { title: 'payments', value: 62 },
            { title: 'credit card segmentation', value: 63 },
            { title: 'personal loan', value: 64 },
            { title: 'loan prediction', value: 65 },
            { title: 'credit card fraud', value: 66 },
            { title: 'money laundering', value: 67 },
            { title: 'account details', value: 68 },
            { title: 'credit card data', value: 69 },
            { title: 'credit card eligibility', value: 70 },
            { title: 'credit card approval', value: 71 },
            { title: 'credit card application', value: 72 },
            { title: 'rbi', value: 73 },
            { title: 'lending club loan', value: 74 },
            { title: 'loan repayment', value: 75 },
            { title: 'predictive modelling', value: 76 },
            { title: 'loan prediction', value: 77 },
            { title: 'loan defaulter', value: 78 },
            { title: 'data analysis', value: 79 },
            { title: 'classification', value: 80 },
            { title: 'data standardization', value: 81 },
            { title: 'KNN', value: 82 },
            { title: 'Logistic Regression', value: 83 },
            { title: 'SVC', value: 84 },
            { title: 'DecisionTreeClassifier', value: 85 },
            { title: 'Clustering', value: 86 },
            { title: 'PCA', value: 87 },
            { title: 'data preprocessing', value: 88 },
            { title: 'recipe', value: 89 },
            { title: 'credit risk', value: 90 },
            { title: 'german credit risk', value: 91 },
            { title: 'data exploration', value: 92 },
            { title: 'credit card default', value: 93 },
            { title: 'accelerated eda', value: 94 },
            { title: 'missing value treatment', value: 95 },
            { title: 'missing value imputation', value: 96 },
            { title: 'missing data', value: 97 },
            { title: 'time series dataset', value: 98 },
            { title: 'time series analysis', value: 99 },
            { title: 'trend identification', value: 100 },
            { title: 'pattern identification', value: 101 },
            { title: 'Testing', value: 102 },
            { title: 'Monitoring', value: 103 },
            { title: 'problemdefinition', value: 104 },
            { title: 'datapreparation', value: 105 },
            { title: 'exploratorydataanalysis', value: 106 },
            { title: 'modelbuilding', value: 107 },
            { title: 'modeltracking', value: 108 },
            { title: 'modelinterpretation', value: 109 },
            { title: 'operationalise', value: 110 },
        ]
    }
    
    ddlCategory = "";
    
    onSubmit() {
        alert('ID: '   this.ddlCategory);
      }

    ngOnInit() {
        this.http.get(`http://[ip address removed]:8083/v1/masterdata/jenkins`).subscribe((data) => {
          console.warn("Data",data)
        });
     }
        
    submitForm(formVal) {
        if (this.uploadForm.invalid) {
            return
        }
        if(this.checkRefrenceValidation(1)){
        
        
        let e = formVal.licenseDate
        let d = new Date(e)
        let  licenceValue;
        if (isNaN( d)) 
         licenceValue='';
        else
        licenceValue= d.toISOString();
        let formObj = {
            title: formVal.title,
            description: formVal.description,
            howToUse: formVal.howToUse,
            size: this.fileToUpload.size,
            type: formVal.type,
            provider: formVal.provider,
            artefactTags: this.artefactTags,
            licenseValidityDate:licenceValue,
            licenseNumber: formVal.licenseNo,
            fileType: formVal.fileType,
            references: this.internalRef,
            externalReferenceUrls: this.externalRef,
        }

        let formData: FormData = new FormData()
        formData.append('artefact', JSON.stringify(formObj))
        formData.append('file', this.fileToUpload, this.fileToUpload.name)

        this.uploadService.sendUploadData(formData).subscribe(
            (res: any) => {
                if (res) {
                    this.error = ''
                    this.hasError = false;
                    this.uploadForm.reset();
                    this.selectedTags = [];
                    this.internalRef=[];
                    this.externalRef=[];
                    this.refHtml=[];
                    this.message = 'Artefact uploaded successfully'
                    this.showMessage = true;
                    setTimeout(function () {
                        this.error = ''
                        this.showMessage = !this.showMessage;
                        this.hasError = false;
                        this.message = '';
                    }.bind(this), 5000);
                }
            },
            err => {

                if (err.message === 'Token Expired') {
                    this.authService.logout()
                }
                //if (err.error && err.error.message)
                  //  this.error = err.error.message;
                 this.error = 'Something went wrong. Please try again';
                this.hasError = true
                this.message = ''
                this.showMessage = true
                this.hasError = true
                this.uploadForm.reset();
                this.selectedTags = [];
                this.internalRef=[];
                this.externalRef=[];
                this.refHtml=[];
                setTimeout(function () {
                    this.error = ''
                    this.showMessage = !this.showMessage;
                    this.hasError = false;
                }.bind(this), 5000);
            }

        )
        }
    }

    //  custom validation
    checkboxSpace(control: AbstractControl) {
        if (control.value && control.value.trim() !== '') {
            return true
        }
        return { checkboxSpace: true }
    }
    // reset form 

    resetForm() {
        this.uploadForm.reset()
        this.selectedTags = [];
        this.message = ''
        this.showMessage = !this.showMessage
        this.error = ''
        this.hasError = false
    }
    // file upload change 
    handleFileInput(files: FileList) {
        this.fileToUpload = files.item(0)
    }

    // tag selection 
    onChange($event) {
        let selected_value = Object.values(
            this.uploadForm.controls['tags'].value
        )
        if (selected_value.length == 7)
            return
        this.artefactTags = []
        this.selectedTags = []
        selected_value.forEach((i: number) => {
            this.selectedTags.push(
                '<span >#'   this.tags[i].title   '</span>'
            )
            this.artefactTags.push({ tag: this.tags[i].title })
        })
    }

// Add Reference 
    pushRef() {

        if(this.checkRefrenceValidation(2)){
        this.refHtml.unshift(
            "<div class='row '> <div class='px-1 col-md-4 inputs refHeaders  mr-3'> "  
            "<span class='px-1 text-grey fontH5 vertcal-middle'>•</span>"  
            " <label class=  '  '> "   this.uploadForm.controls['refClassification'].value   "</label></div> "  
            " <div class='p-l-0 col-md-6 inputs refHeaders'>  <label class=''> "  
            this.uploadForm.controls['refLink'].value  
            "</label> </div> </div>"
        )
        this.uploadForm.get('refClassification').reset('');
        this.uploadForm.get('refLink').reset('');
        }
    }

//  reference validation
    checkRefrenceValidation(checkvalue:number) {
        let classificationControl = this.uploadForm.get('refClassification');
        let linkControl = this.uploadForm.get('refLink');
        let classValue = classificationControl.value == '' || classificationControl.value == null ? false : true;
        let linkValue = linkControl.value == '' || linkControl.value == null  || linkControl.value.trim() ==''? false : true;
        let isvalid;
        if (checkvalue==1)
        {
         isvalid =  (classValue && linkValue) || (!classValue && !linkValue) ? true :false;
        }else
        { isvalid =  (classValue && linkValue)  ? true :false;
            
        }
        
        if (isvalid==1) {
            if (classValue && linkValue) {
                if (classificationControl.value == 'internal')
                    { 
                     let findkey = this.internalRef.find(o => o.id === linkControl.value.trim());
                      if(findkey)  
                      {this.showReferenceValidError("Reference Id already in list");
                        return ;
                       }
                      else
                      this.internalRef.push({ id: linkControl.value.trim() });
                    }
                else
                 {   
                    this.externalRef.push({ url: linkControl.value.trim() });
                 }
            }
        }
        else {
            this.showReferenceValidError();
            return false;
        }
       return true;
    }

    showReferenceValidError(error:String='Classification and link both are required to enter reference') {
        this.error = error;
        this.hasError = true
        setTimeout(function () {
            this.error = ''
            this.hasError = false;
        }.bind(this), 5000);
    }
    checkNumber(value:any='')
    {
        if(isNaN(value))
        {this.showReferenceValidError('Reference id  is not valid');
        return false;
       }
       return true;
    }
}

request.interceptor.ts

import { Injectable } from '@angular/core'
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
} from '@angular/common/http'
import { AuthService } from '../services/auth.service'
import { Observable } from 'rxjs'

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
    constructor(public authService: AuthService) {}
    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        let ignore =
            typeof request.body === 'undefined' ||
            request.body === null ||
            request.body.toString() === '[object FormData]' || // <-- This solves your problem
            request.headers.has('Content-Type')

        if (ignore) {
            request = request.clone({
                setHeaders: {
                    accept: 'application/json',
                    ...(this.authService.getToken()
                        ? { authorization: this.authService.getToken() }
                        : { authorization: '' }),
                },
            })
            return next.handle(request)
        }
        request = request.clone({
            setHeaders: {
                'content-type': 'application/json',
                accept: 'application/json',
                ...(this.authService.getToken()
                    ? { authorization: this.authService.getToken() }
                    : { authorization: '' }),
            },
        })

        return next.handle(request)
    }
}

CodePudding user response:

To know what is going wrong with your http call, inspect your request in the network pane. Take every information and report it in postman (such as URL, parameters and all headers) then it should break exactly as in your browser. Once this is done, you will be able to find out what is going wrong by comparing/adding/changing headers.

But first of all, i see that you actually have 7 headers in your postman. Are these headers present in your request in angular too?

If your problem still persists, please provide us a screenshot of the request details in the network pane of your browser.

Also is there any message in your console?

Concerning your token, most of the time token errors are returning a 401, not a 403, but ensure yourself that your token are exactly the same values (check the end, not only the start, all jwt tokens starts with ey...)

CodePudding user response:

My guess - you forget to provide an interceptor:

@NgModule({
  // ...
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }
  ]
})
  • Related