Error encountered when attempting to retrieve response from Java Servlet using HttpClient

I'm encountering an issue where I am receiving a null response in Angular when attempting to post to a httpservlet (Java) in a WebSphere Application Server environment.

The objective is to call an API for logging in. However, I am getting a null response, which hinders any further action with the response.

I have tried sending my parameters as form data with the content-type application/x-www-form-urlencoded;charset=UTF-8 and as query parameters without specifying a content-type.

In both scenarios, I can successfully log in and receive a 200 response with header details in my browser.

This is the code snippet for my POST request:

return this.http.post(this.contextRoot.getHost() + 'osa-kantoor-ws/api/auth/login?' + param1 + "&" + param2,null, this.httpOptions).map((res : Response) => {
      localStorage.setItem('currentUser', JSON.stringify(username));
      return res;
});

The current header information set up is as follows:

httpOptions = {
    headers: new HttpHeaders({'Content-Type' : 'application/json', 'Accept':  'application/text'}),
    params: {}
};

While the local storage item is being set successfully, the response remains null.

Here is the subscribe function being used:

login() {
    this.loginService.login(this.loginForm.value.userName,this.loginForm.value.password)
        .subscribe(
            data => {
                console.log(data);
                this.router.navigate([this.returnUrl]);
            },
            error => {
                console.log(error);
                this.loginfail = true;
            }
         );
}

Upon inspecting the browser information for the response header, I obtained the following details:

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

If anyone can provide insight into what might be causing this issue, it would be greatly appreciated.

Below is the original method that was referenced:

login(username: string, password: string) {
    let param1: string = encodeURIComponent('userName') + '=' + encodeURIComponent(username);
    let param2: string = encodeURIComponent('password') + '=' + encodeURIComponent(password);
    let formParams: string = param1 + '&' + param2;
    return this.http.post(this.contextRoot.getHost() + 'osa-kantoor-ws/api/auth/login', formParams, this.httpOptions).map(response=> {
      localStorage.setItem('currentUser', JSON.stringify(username));
      console.log(response);
      return response;
    });
}

Answer №1

Many thanks AJT_82,

By adding 'observe: response' to the configuration, I was able to resolve the issue.

I am now receiving the expected response. It appears that the default response is 'observe: body'.

Here is my updated HTTP config:

  httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8','Accept':  'application/xml'}),
    observe: 'response'
  };

As a result, my response now looks like this:

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

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 kotlinx.serialization to deserialize a JSON array into a sealed class

Stored as nested JSON arrays, my data is in rich text format. The plaintext of the string and annotations describing the formatting are stored in text tokens. At decode time, I aim to map the specific structure of these nested JSON arrays to a rich Kotlin ...

Sending selected IDs from the JSON data

In my project, there is a JSON file named "workers" which contains information about all the workers. I have created a select component to display the names of the workers like this: https://i.sstatic.net/0Glyf.png Currently, I am selecting some workers ...

io-ts: Defining mandatory and optional keys within an object using a literal union

I am currently in the process of defining a new codec using io-ts. Once completed, I want the structure to resemble the following: type General = unknown; type SupportedEnv = 'required' | 'optional' type Supported = { required: Gene ...

Issue encountered while attempting to enclose a function within another function in Typescript

I'm attempting to wrap a function within another function before passing it to a library for later execution. However, I'm encountering various Typescript errors while trying to utilize .apply() and spread arguments. The library mandates that I ...

Tips for updating values in an Angular model and pushing it to an array with the specified index

I am currently facing an issue with my Angular Model as I attempt to add it to an array in order to generate repeated fields. The purpose of this array is to then be looped through in order to create HTML fields within a component. However, during the proc ...

The combination of React, Typescript, and MaterialUI Paper results in a stunning design with a sleek and

Whenever I include <Paper elevation={0} /> within my react component, I encounter the following issue: Cannot read properties of undefined (reading 'background') TypeError: Cannot read properties of undefined (reading 'background&apos ...

Encountering issues when utilizing the 'got' package

I encountered an issue while using 'got' version '11.8.3', resulting in the following error: /app/node_modules/got/dist/source/core/index.js:696 throw new TypeError('The payload has been already provided'); ^ TypeError: The p ...

The requested property map cannot be found within the Array

I am working on a project using redux with react typescript. I have an external JSON file that contains employee data categorized by department id. To properly map the data with types in my application, I have created specific types. Check out this demo o ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Why is the navbar toggle malfunctioning despite having all necessary dependencies in Angular?

Recently, I've been tackling the challenge of implementing a Navbar with collapse menu and dropdown links using Bootstrap 4 and Angular 6. However, I've hit a roadblock as the Navbar is not functioning as expected. Although the elements seem to r ...

Using TypeScript to access the event.target.elements property when handling a form submission event

In my React code, I have successfully implemented the following logic in JavaScript: function handleSubmit(event) { event.preventDefault() console.dir(event.target[0].value) console.dir(event.target.usernameInput.value)'EventTarget'. cons ...

What causes the RxJS pipe not to run in ngOnInit when the Observable is initialized at the class level?

Why doesn't the pipe in the ngOnInit method get triggered when the Observable is initialized at the class property declaration level and unwrapped by the async pipe? Although I am aware that I can initialize the Observable in the ngOnInit method itse ...

An empty page persistently remains blank due to routing issues in Angular

Whenever I click on the "Portfolio" link, https://i.sstatic.net/RTxkC.png The Portfolio page doesn't appear as expected (shown below) https://i.sstatic.net/wJBP8.png I'm having trouble understanding the routing system. Below is the structure ...

Leveraging OAuth 2 with Google

I'm currently working on implementing Google API for user authentication. I have successfully managed to authenticate users, but I am struggling with redirecting users after Sign In and implementing Sign Out functionality. I have been referring to th ...

Refresh a page automatically upon pressing the back button in Angular

I am currently working on an Angular 8 application with over 100 pages (components) that is specifically designed for the Chrome browser. However, I have encountered an issue where the CSS randomly gets distorted when I click the browser's back button ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

How to build an angular2/typescript project without including node_modules in team foundation 2013?

I am facing an issue with my angular2 application where it works fine locally but fails to build on the build server. I want to avoid checking in the massive number of files (29,000) within the node_modules directory as part of our build process (local, te ...

Tips for implementing a multi-layered accumulation system with the reduce function

Consider the following scenario: const elements = [ { fieldA: true }, { fieldB: true }, { fieldA: true, fieldB: true }, { fieldB: true }, { fieldB: true }, ]; const [withFieldA, withoutFieldA] = elements.reduce( (acc, entry) => ...

Issue with nestjs build due to ts-loader module in dev-dependency

I've encountered a Module Error with ts-loader during a docker build ERROR [6/6] RUN nest build 3.9s ------ > [6/6] RUN ...

Sending Node.js Results to Web Interface

Currently, I am exploring the use of Node.js to run SQL SELECT statements on a table in MariaDB. Through the mySQL module, I have managed to establish a connection with the database and execute the query successfully. The results are displayed in the conso ...