The call to 'setRequestHeader' on 'XMLHttpRequest' was unsuccessful due to the object's state not being OPENED

While developing an angular application with a restful API get(), I encountered a few errors such as unauthorization error:401 which I managed to resolve. However, now I am facing another error that seems quite straightforward. I even tried adding the CORS package but to no avail.

I have been tirelessly searching for solutions but so far, my efforts have been in vain. I even went back and revised my previous question but received no response.

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();
}
}

https://i.sstatic.net/vtXDB.png

Answer №1

Referencing the Angular guide

It is recommended to utilize the following approach (for Angular 4.3 and above / Ensure to use HttpClientModule instead of the old 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')
          });
  }
}

Then in a component

<yourservice>.makeMyRequest().subscribe(data => {
     // Customize as needed
});

Answer №2

For me, the issue stemmed from a trailing \n character in my header's authentication value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using FormArray in Angular 2 with ControlValueAccessor

My child component manages an array of input controls and I would like to implement a form control over this child component. I am passing an array of JSON objects and I am wondering what is the correct way to bind the parent form to the child component&a ...

1. "The power of three vows in the world

I encountered an issue while making three HTTP Post requests in my code. The first two requests are successful, and upon debugging the code, they return the correct values. However, the third request returns undefined. The reason behind making these three ...

The NbDatePicker does not display certain Spanish names

One issue I'm facing is with the Nb-DatePicker component in my project. I tried using {provide: LOCALE_ID, useValue: "es-MX"} in my app.component to display it in Spanish. However, when February, April, May, August, or December are selected, ...

Sending a POST request that is attempting to insert empty values into an MS SQL database

Here is the code I am working with - onSubmit(){ var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let postParams = { firstName : this.firstName, lastName : this.lastNa ...

Creating a TypeScript type based on the static values of a class

In my Market class, there is only one parameter: name. class Market { name: string constructor(name: string) { this.name = name } } Next, I have a Markets class that contains a static collection of multiple markets. class Markets { static M1 ...

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

Encountering errors after updating to Angular Material version 6.4.7

I recently updated my Angular/Material to version 6.4.7 in my Angular2 project, but now I am experiencing a number of errors. I suspect that this may be due to the fact that my Angular/CLI version is at 1.7.4. Is there a way for me to successfully integra ...

What is the best way to transform an Observable<Observable<HttpEvent<any>>> into an Observable<HttpEvent<any>> within the Angular AuthInterceptor service?

export class AuthInterceptor implements HttpInterceptor { constructor(private usersService: UsersService){} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return this.usersService ...

Deriving types from object combinations

Can the Foo type be 'flattened' to return { A?: string; B? number } in the code snippet below? type Foo = { A: string } | { B: number } type Flatten< T, Keys extends keyof T = T extends any ? keyof T : never, > = { [K in Keys]?: T[K] } ...

Creating a Bottom Sliding Menu in Ionic 2

Hey there! I'm working on something that might not fit the typical definition of a sliding menu. It's not for navigation purposes, but rather to house some data. My idea for this actually comes from Apple Maps: https://i.stack.imgur.com/hL1RU.jp ...

Discovering a specific string within an array of nested objects

Seeking guidance on creating a dynamic menu of teams using JavaScript/TypeScript and unsure about the approach to take. Here is an example dataset: const data = [ { 'name': 'Alex A', 'agentId': '1225& ...

Is there a way to trigger a custom event from a Web Component and then intercept it within a React Functional Component for further processing?

I'm facing an issue with dispatching a custom event called "select-date" from a custom web component date picker to a React functional component. Despite testing, the event doesn't seem to be reaching the intended component as expected. Below is ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

Angular2 - Showing parameters in modal interface

I am working on an Angular5 app and have a component.html file with a function called markerClick that opens a modal. However, I am facing challenges in displaying the item.lat parameter in the modal and would appreciate your assistance. Below is the code ...

The angular2-markdown module encounters errors

I am currently working on implementing a markdown editor in a form within my Angular2 project. To achieve this, I have installed the angular2-markdown module. However, I encountered an error when trying to use it, specifically: "marked" is not a function. ...

What is the best way to handle an OR scenario in Playwright?

The Playwright documentation explains that a comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. However, when I try to implement this, it doesn't seem to work as expected. For exam ...

Troubleshoot TypeScript API within Angular 12 using Chrome debugger

I'm having trouble finding a solution on SO. Can anyone help me debug and check the code snippet below for hello? getHero(): void { const id = parseInt(this.route.snapshot.paramMap.get('id') !, 10); this.heroService.getHero(id) .sub ...

After upgrading from angular version 7.0 to 8.0, I realized that the target in the tsconfig.json file remained unchanged

After running the command ng update @angular/cli @angular/core, I successfully updated my Angular 8 version. The updated versions are as follows: Angular CLI: 8.0.1 Node: 10.15.3 OS: linux x64 Angular: 8.0.0 ... animations, cdk, common, compiler, compiler ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

Performing bulk operations on all selected rows in a table using Angular 6

Within my Angular 6 web application, there is a table with checkboxes in each row. My goal is to be able to perform bulk actions on the selected rows, such as deleting them. One approach I considered was adding an isSelected boolean property to the data m ...