在Angular 5中获得400错误请求的JSON响应

时间:2018-12-20 04:21:36

标签: angular amazon-s3 angular5

我正在尝试从Angular 5调用Amazons3的REST API。在这里,我收到了400个错误的请求

很长一段时间都面对这个问题,真的需要对问题所在的相同或至少建议进行修复吗?

下面是我如何从Angualar调用REST,我如何共享控制台屏幕截图enter image description here

Interceptor.service.ts

    import { Injectable, Inject } from '@angular/core';
import {HttpInterceptor,HttpHandler,HttpRequest,HttpEvent,HttpClient,HttpHeaders,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import { LocalStorageService } from 'angular-2-local-storage';
import { LogserService } from '../logser.service';

import { Router  } from '@angular/router';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/forkJoin';
import { BatchService } from '../pages/config/batchnew/batch.service';




@Injectable()
export class MainInterceptorService implements HttpInterceptor {
    public error:boolean = true;
    constructor(public localStorage:LocalStorageService,
        public router:Router,public http:HttpClient,
        public loginService:LogserService,
      public BatchServ:BatchService
    ){

    }
//@Inject(Window) private window: any

  intercept(req:HttpRequest<any>,next:HttpHandler):Observable<HttpEvent<any>> {
    // console.log("interceptor",req)
    this.error=true;
    let url:any = req.url
    url = url.split('/')
    url =url[url.length-1]
    // console.log('url',url)
    // console.log(localStorage.get("token"))
    if (url =="authenticateuser"){
        const request = req.clone({
            headers:new HttpHeaders({
                // 'VitalAuthorization':  window.localStorage.getItem('token')
            })
        })
        // console.log("interceptorHeaderLogin",request)
        return  next.handle(request).do((event: HttpEvent<any>) => {
              if (event instanceof HttpResponse) {
                        // do stuff with response if you want
                    //  console.log("getting 39")
              }
            }, (err: any) => {
              if (err instanceof HttpErrorResponse) {
                if (err.status === 401) {
                  // redirect to the login route
                            // or show a modal
                    //      console.log("getting 46")

                  alert('UnAutorized access');
                  // console.log(err)
                }
              }
            });
    }else{
        //  console.log("Line 51")
        const request = req.clone({
            headers:new HttpHeaders({
                        'Authorization':  window.localStorage.getItem('token')

            })
            })

        // console.log("interceptorHeader",request)
        return  next.handle(request).do((event: any) => {
           // console.log("getting in interseptor")
}, (err: any) => {
           //   console.log('error401')
                // console.log('interceptorStatus',err.statusCode)
              if (err instanceof HttpErrorResponse) {
                if (err.status == 501) {
                  // redirect to the login route
                  // or show a modal
                        //  console.log('error72')
                  if( this.error===true){
                        this.error=false;
                        // this.router.navigate(['/login/'+this.localStorage.get('url')])
                        alert('Session expired ...');
                        let data = JSON.parse(this.localStorage.get('userData'))
                        this.BatchServ.createLogin(data).subscribe((data:any) => {
                            if (data.validAuthentication && data.validAuthentication != "" && data.validAuthentication != "null" && data.validAuthentication !="false"){
                                             window.localStorage.setItem('token',data.validAuthentication);
                                    //       console.log("line83")
                                console.log(window.localStorage.getItem('token'));
                                window.location.reload();
                                         }
                                         else{

                                         }
                                     });



                  }
                  console.log(err)
                }
              }
            });

    }

    }

   }

batch.service.ts

import {Injectable,OnInit,EventEmitter} from '@angular/core';
import { HttpClient, HttpHeaders ,HttpParams} from '@angular/common/http';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import { Batch } from './batch.model';
import { Api_urls } from './api_urls.model';
import { Ng4LoadingSpinnerService } from 'ng4-loading-spinner';
import { LocalStorageService } from 'angular-2-local-storage';




@Injectable()
export class BatchService implements OnInit {

  public userId:any="user9";

  private httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' })
};

  private messageSource = new BehaviorSubject<any>('default');
  currentMessage = this.messageSource.asObservable();

   private filterSource = new BehaviorSubject<any>('default');
  filteMessage = this.filterSource.asObservable()

  private filterClaimSource =  new BehaviorSubject<any>('default');
  filterClaim = this.filterClaimSource.asObservable()

  private filterClaimId =  new BehaviorSubject<any>('default');
  filterId = this.filterClaimId.asObservable()

  private filterdob = new BehaviorSubject<any>('default');
  filterDob = this.filterdob.asObservable()

   private ClaimSource =  new BehaviorSubject<any>('default');
  ClaimMessage = this.ClaimSource.asObservable()

  private ClaimTranc =  new BehaviorSubject<any>('default');
  ClaimtrancMessage = this.ClaimTranc.asObservable()

  private publishClaims = new BehaviorSubject<any>('default');
  publishMessageSource = this.publishClaims.asObservable()

  private refreshMenuObj = new BehaviorSubject<any>(false);
  public refreshVmenu =  this.refreshMenuObj.asObservable()
  public dashboadrdData = new EventEmitter();
  public professionalFormStatus = new EventEmitter();
  public addPhysician = new EventEmitter();
  base_url:any;
  private Api_urls:any;
  headerdata:any=[];
  //private batchUrl:any = '/assets/data/batchstatus.json';
  // Api_urls: Api_urls = new Api_urls();

  // public logoutUrl = "";
  //public uploadUrl = "https://je2ngjw0w0.execute-api.us-east-1.amazonaws.com/dev/fileupload";
  // public form1url= "";


  constructor(private http:HttpClient, private localStorage:LocalStorageService,public spinner:Ng4LoadingSpinnerService) {
     if(this.localStorage.get('app_mode')){
      // this.base_url = this.localStorage.get('app_mode');
    }
    else{
      console.log("its not working")
      this.getUrl();
    }

     // console.log(this.base_url)
     if(this.localStorage.get('userID') !=null){
       this.userId = this.localStorage.get('userID')
     }else{
       this.userId = "user9"
     }

      // console.log(this.localStorage.get('userID'))    


      // if(this.localStorage.get('app_mode')){
      //   // this.baseUrl = this.localStorage.get('app_mode');
      // }


  }
  public headerUrl:string = '/assets/data/batchstatus.json';
  ngOnInit(){
    // this.spinnerService.hide();
    // this.localStorage.set('app_mode',this.app_mode);
    // console.log(this.localStorage.get('isLoggedin'))
    // if(this.localStorage.get('isLoggedin')){
    //   this.router.navigate(['pages/dashboard']);

    // }
    // console.log(this.localStorage.get('user'))
    this.getUrl()     
  }

  getUrl () {
    console.log('getting')
    this.http.get('assets/api_urls.json').subscribe((res) => {
        // console.log("inUrl")
         // return (res);
         this.Api_urls= res;
         // console.log('newUrls',this.Api_urls)

       },(error)=>{
         // this.spinner.hide()
         // alert("Network Error")

       });    
  }

1 个答案:

答案 0 :(得分:0)

此错误与您获取数据的http url或路径有关。该错误不应该是一个大问题,它与您的服务调用错误的地址有关。