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

问题描述 投票:0回答:2

我无法将标头设置为我的请求网址。请求必须发送上传文件对象,请求授权所需的JSON和标头。该请求不附加标题,因此api向我发送401未经授权的响应。我的是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");
                    }
                };
            }
angular typescript http-headers http-post
2个回答
0
投票

请试试这个,

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

像这样声明Header选项。

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

并使用此标题选项likethis

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

希望这对你有用。


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' });
...
© www.soinside.com 2019 - 2024. All rights reserved.