尽管存在XMLHttRequest错误,但Angular2发布请求

时间:2016-12-20 19:54:01

标签: ajax http angular xmlhttprequest angular2-http

我向远程API发送请求。 API需要一点时间才能继续。

经过这么短的等待时间,我可以在网络选项卡中看到一个HTTP 200.在回复中,我得到了正确的预期信息。 API端的一切工作正常。

在控制台上进行BIT,我看到我遇到了XMLHttpRequest错误。

为什么,特别是如果我有一个XMLHttpRequest错误,POST是用200完成的?不应该被阻止"通过Angular2?

意外的结果是:我的文件被API正确上传和处理,但在Angular2中,它会触发我调用的ERROR部分

例如,如果我使用https://resttesttest.com/,它似乎遇到了相同的错误,但它没有完成POST:

  

哦不! Javascript返回了一个   HTTP 0错误。这可能发生的一个常见原因是你   从未包含的服务器请求跨域资源   响应中适当的CORS头。

此次通话的Angular 2代码

this.http
    .post(this.documentUploadAPIUrl, formData, options)
    .subscribe(
      res => {
        this.responseData = res.json();
        console.log(this.responseData);
        console.log('Uploaded a blob or file!');
      },
      error => {
        console.log('Upload failed! Error:', error);
      }
    );

Console

1 个答案:

答案 0 :(得分:2)

尝试将xmlHttpRequest的withCredential属性设置为true,这将发送由浏览器管理的凭据,在角度2中你可以这样做

    import { RequestOptions } from '@angular/http';


    this.http
      .post(this.documentUploadAPIUrl, formData, this.post_options)
      .subscribe(
        res => {
         this.responseData = res.json();
         console.log(this.responseData);
         console.log('Uploaded a blob or file!');
        },
        error => {
         console.log('Upload failed! Error:', error);
        }
       );



post_options() {
   return new RequestOptions({ method: 'post', withCredentials : true  });
}
相关问题