XMLHttpRequest.setRequestHeader()

时间:2017-02-28 12:12:04

标签: angularjs csv angular

我正在尝试为XMLHttpRequest.setRequestHeader()设置参数,以便能够导入csv文件。虽然,我确信它能够识别登录用户的令牌,但是当我提交csv或xlxs文件时,我收到错误。可能有什么不对?

//file service
   public progress$;
   public progressObserver;
   public progress : number;
   public headers:string;


    constructor (private auth:AuthenticationService) {
        this.progress$ = Observable.create(observer => {
            this.progressObserver = observer
        }).share();
    }

     makeFileRequest (url: string, params: string[], files: File[]) {
        return Observable.create(observer => {
            let formData: FormData = new FormData(),
                xhr: XMLHttpRequest = new XMLHttpRequest();

            for (let i = 0; i < files.length; i++) {
                formData.append("uploads[]", files[i], files[i].name);
            }

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        observer.next(JSON.parse(xhr.response));
                        observer.complete();
                    } else {
                        observer.error(xhr.response);
                    }
                }
            };

            xhr.upload.onprogress = (event) => {

                this.progress = Math.round(event.loaded / event.total * 100)
                this.progressObserver.next(this.progress);
            };


            xhr.open('POST', url, true);
            xhr.setRequestHeader(this.headers, this.auth.token);
            xhr.send(formData);


        });
    }
}
//Exception

ErrorHandler</ErrorHandler.prototype.handleError http://localhost:4200/main.bundle.js:44671:9
    PlatformRef_</PlatformRef_.prototype._bootstrapModuleFactoryWithZone/</<.next http://localhost:4200/main.bundle.js:29085:65
    EventEmitter</EventEmitter.prototype.subscribe/schedulerFn< http://localhost:4200/main.bundle.js:30598:36
    SafeSubscriber</SafeSubscriber.prototype.__tryOrUnsub http://localhost:4200/main.bundle.js:632:13
    SafeSubscriber</SafeSubscriber.prototype.next http://localhost:4200/main.bundle.js:581:17
    Subscriber</Subscriber.prototype._next http://localhost:4200/main.bundle.js:534:9
    Subscriber</Subscriber.prototype.next http://localhost:4200/main.bundle.js:498:13
    Subject</Subject.prototype.next http://localhost:4200/main.bundle.js:3046:17
    EventEmitter</EventEmitter.prototype.emit http://localhost:4200/main.bundle.js:30590:54
    NgZone</NgZone.prototype.triggerError http://localhost:4200/main.bundle.js:31404:56
    NgZone</NgZone.prototype.forkInnerZoneWithAngularBehavior/this.inner<.onHandleError http://localhost:4200/main.bundle.js:31383:17
    Zone$1</ZoneDelegate</ZoneDelegate.prototype.handleError http://localhost:4200/main.bundle.js:102771:17
    Zone$1</Zone</Zone.prototype.runTask http://localhost:4200/main.bundle.js:102692:25
    ZoneTask/this.invoke http://localhost:4200/main.bundle.js:102870:28

//错误

onChange
file.ts:27 FileList {0: File, length: 1}
:4200/#/dashboard/customer:1 XMLHttpRequest cannot load http://localhost:9000/api/v1/file/food. Request header field undefined is not allowed by Access-Control-Allow-Headers in preflight response.
error_handler.js:47 EXCEPTION: 
ErrorHandler.handleError @ error_handler.js:47
next @ application_ref.js:272
schedulerFn @ async.js:82
SafeSubscriber.__tryOrUnsub @ Subscriber.js:223
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
ZoneDelegate.handleError @ zone.js:236
Zone.runTask @ zone.js:157
ZoneTask.invoke @ zone.js:335
Subscriber.js:227 Uncaught 
SafeSubscriber.__tryOrUnsub @ Subscriber.js:227
SafeSubscriber.next @ Subscriber.js:172
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ async.js:74
NgZone.triggerError @ ng_zone.js:278
onHandleError @ ng_zone.js:257
ZoneDelegate.handleError @ zone.js:236
Zone.runTask @ zone.js:157
ZoneTask.invoke @ zone.js:335
file.ts:20 progress = NaN

1 个答案:

答案 0 :(得分:1)

您在此行中遇到问题

xhr.setRequestHeader(this.headers, this.auth.token);

在您的代码中,您尚未向this.headers分配任何内容,因此最终会添加一个名为undefined的标头,您的服务器将无法理解该标头。

以下是您应该如何做的示例。正如VadimB所提到的,您仍然需要将自定义标头添加到服务器Access-Control-Allow-Headers中的cors配置中

// Make sure this.auth.token is assigned your token
xhr.setRequestHeader('Authorization', this.auth.token);

// sending jwt in most scenarios
xhr.setRequestHeader('Authorization', 'Bearer xxx.xxx.xxx'); 

请阅读xhr上的文档,了解在何时何地使用的内容。

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest