无法在'XMLHttpRequest'上执行'setRequestHeader':对象的状态必须是打开的

时间:2017-11-29 08:24:43

标签: angular typescript restful-authentication

我一直在使用restful API get()开发一个角度应用程序。我有一些错误,如未授权错误:401已经解决。现在我收到了这个直截了当的错误。我也尝试过添加CORS包。

我一直在寻找徒劳的解决方案。我重新编辑了我之前的问题,但似乎没有回应。

my-httpservice.service

import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from 
'@angular/http';


@Injectable()
export class MyHttpserviceService {

constructor(private http:Http) {}

server_grid_Get(){

var request = new XMLHttpRequest();
var user = "Root";
var pass = "root";

//Use Basic authentication

request.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
request.setRequestHeader('Content-Type','application/json');
request.setRequestHeader('Access-Control-Allow-Credential','true');

 request.open("GET", "http://192.100.00.000:0000/_db/xxxxx_app/_api/document/wsdl_test/4934434",true);

  return this.http.get("http://192.100.00.000:0000/_db/xxxx_app/_api/document/wsdl_test/4934434").map(response => response.json());


 request.addEventListener('load', function(event) {
    if (request.status >= 200 && request.status < 300) {
        console.log(request.responseText);
    } else {
        console.warn(request.statusText, request.responseText);
    }
  });
  request.send();
}
}

enter image description here

2 个答案:

答案 0 :(得分:3)

来自angular guide

你应该使用类似的东西(角度4.3+ /确保你使用HttpClientModule而不是旧的HttpModule)

@Injectable()
export class MyHttpserviceService {      
  constructor(private http:HttpClientModule) {}
  private makeMyRequest () {
       return this.http.get("http://192.100.00.000:0000/_db/xxxx_app/_api/document/wsdl_test/4934434", {
            headers: new HttpHeaders()
                .set('Authorization', 'Basic ' + btoa(user + ':' + pass))
                .set('Content-Type','application/json')
                .set('Access-Control-Allow-Credential','true')
          });
  }
}

然后在组件中

<yourservice>.makeMyRequest().subscribe(data => {
     // anything you want
});

答案 1 :(得分:0)

在我的情况下,我的标头在auth标头值的末尾有一个\n字符,它引起了所有混乱