无法在Angular7中向我的请求API添加标头

时间:2019-02-12 05:31:59

标签: angular typescript http-headers http-post

我无法将标题设置为我的请求URL。请求必须发送上传文件对象,请求JSON和授权所需的标头。该请求未附加标头,因此api向我发送了401未经授权的响应。 Mine是Angular 7应用程序。我正在使用@ angular / http进行标头构建。请在下面找到html&ts代码。

任何快速修复都对我有很大帮助。

HTML代码

<div class="font-weight-bold text-center pageSpacing">
        Thanks America <img src="assets/images/add-icon.png"
            style="width: 3%; float: right;" class="pointer"
            (click)="openWindowCustomClass(content)">
    </div>
 <ng-template #content let-modal>
    <div class="modal-header" style="border-bottom: 0px;">
        <div class="pointer" (click)="fileInputImage.click()">
            <img src="assets/images/upload-image_80.png" style="width: 25%;">Upload
            Image
        </div>
        <div class="pointer" (click)="fileInputVideo.click()">
            <img src="assets/images/upload-video_80.png" style="width: 25%;">Upload
            Video
        </div>
    </div>
    <div class="modal-body text-center">
        <span
            style="visibility: hidden; position: absolute; overflow: hidden; width: 0px; height: 0px; border: none; margin: 0; padding: 0">
            <input type="file" #fileInputImage accept='image/*'
            (click)="isUpload='i'" (change)="preview(fileInputImage.files)"
            ng2FileSelect [uploader]="uploader" />
        </span> <span
            style="visibility: hidden; position: absolute; overflow: hidden; width: 0px; height: 0px; border: none; margin: 0; padding: 0">
            <input type="file" #fileInputVideo accept='video/*'
            (click)="isUpload='v'" (change)="preview(fileInputVideo.files)"
            ng2FileSelect [uploader]="uploader" />
        </span>
    </div>
    <div class="modal-footer"
        style="border-top: 0px; justify-content: center;">
        <form [formGroup]="commentPopup" (ngSubmit)="onSubmit()">
            <div class="form-group">
                <textarea type="text" rows="5" maxlength="400"
                    formControlName="comment" class="form-control"
                    placeholder="Enter your comment here"
                    [ngClass]="{ 'is-invalid': submitted && f.comment.errors }"></textarea>

            </div>
            <div class="form-group text-center">
                <button type="button" class="btn btn-light"
                    (click)="modal.close('Close click');clearPreview();">Cancel</button>
                &nbsp;
                <button (click)="uploader.uploadAll()" class="btn btn-primary"
                    [disabled]="!uploader.getNotUploadedItems().length">Post</button>
            </div>
        </form>
    </div>
    </ng-template>

TS文件代码:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {  FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Headers } from '@angular/http';

constructor(private httpService: HttpClient, private modalService: NgbModal, private formBuilder: FormBuilder) { 
     this.isUpload = '';
    }

    openWindowCustomClass(content) {
        this.modalService.open(content, { size: 'sm' });
    }
      validation() {
        this.commentPopup = this.formBuilder.group({
            comment: ['', Validators.required]
        });
    }
    get f() { return this.commentPopup.controls; }

    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.commentPopup.invalid) {
            return;
        }
    }

preview(files) {
        if (files.length === 0)
            return;

        var mimeType = files[0].type;
        if (mimeType.match(/image\/*/) == null && mimeType.match(/video\/*/) == null) {
            this.message = "Only images / videos are supported.";
            return;
        }
        var reader = new FileReader();
        this.imageOrVideoPath = files;
        reader.readAsDataURL(files[0]);
        reader.onload = (_event) => {
            this.imgOrVideoURL = reader.result;
        }
    }
    clearPreview() {
        this.validation();
        this.imgOrVideoURL = null;
        this.imageOrVideoPath = null;
        this.comment = null;
        this.isUpload='';
    }
    ngOnInit() {
        this.fileUpload();
        this.validation();
    }



      public uploader: FileUploader = new FileUploader({url: this.imageUploadUrl, headers:this.headers,  method: 'POST' });
            fileUpload() {
 this.authHeaders.headers = [{ name: 'userId', value: '1234' },
            { name: 'deviceKey', value: '9999-8888-7777' }];

                this.uploader.onBuildItemForm = (item, form) => {
                    form.append("content","TESTING");
                    form.append("author", "username");
                };
                 this.uploader.onBeforeUploadItem  = (item) => { 

        this.uploader.setOptions(this.authHeaders); 
                  };
                this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
                this.uploader.onCompleteItem = (item: any, response: any, status: any, headers: any) => {
                    console.log('ImageUpload:uploaded:', item, status, response);
                    if (status === 200) {
                        alert('File uploaded successfully');
                        this.uploadedResponse = response;
                    } else {
                        alert("something went wrong");
                    }
                };
            }

2 个答案:

答案 0 :(得分:0)

请尝试一下

import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';

声明这样的标头选项。

const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json','Access-Control-Allow-Origin': 'http://localhost:3000'})
};
const apiUrl = "http://localhost:3000/customer";

并使用此标头选项

  getBook(id: string): Observable<any> {
const url = `${apiUrl}/${id}`;
return this.http.get(url, httpOptions).pipe(
  map(this.extractData),
  catchError(this.handleError));
 }

希望这对您有用。

答案 1 :(得分:0)

FileUploader选项不是Headers中的@angular/http,而是具有名称和值属性的简单对象数组。

执行以下操作:

...
this.headers = [
  {name: 'userInfoId', value: '1'},
  {name: 'deviceKey', value: '5555-00-90p0'},
]
public uploader: FileUploader = new FileUploader({url: this.imageUploadUrl, headers:this.headers,  method: 'POST' });
...