Unable to do post request with HttpClient in angular using proxy config with solution

Rahul Kumar Jain

While I am trying to make post request in HttpClient getting the below error while same with rest client giving proper response. Same with angular 1 $http service is working as expected.

Tried multiple ways but neither post nor get method is working. I am using angular-cli in which I have configured proxy.config.json

{
    "/api/*":{

        "target":"http://10.104.40.14:8290/my_app",
        "secure":false,
        "logLevel":"debug"
    }
}

// error code

 zone.js:2933 POST http://localhost:4200/api/security/login 401 (Unauthorized)
     <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>Error 401 Unauthorized</title>
    </head>
    <body><h2>HTTP ERROR 401</h2>
    <p>Problem accessing /de_prp/error. Reason:
    <pre>    Unauthorized</pre></p>
    </body>
    </html>

Here is my auth.service.ts file

    import { Injectable, OnInit } from '@angular/core';

   import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
        import { RequestOptions, Headers } from '@angular/http';
        import { URLSearchParams } from '@angular/http';
        @Injectable()
        export class AuthService implements OnInit {
          constructor(private http: HttpClient) { }

          ngOnInit(): void {

          }


          login(username, password, rememberMe) {
            console.log(username, password, rememberMe);

            //const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
            const body = JSON.stringify({ username: username, password: password });
            const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
            this.http.post("/api/security/login", body, { headers: headers }).subscribe(
              res => {
                console.log(res);
              },
              (err: HttpErrorResponse) => {

                console.log(err.error);
                console.log(err.name);
                console.log(err.message);
                console.log(err.status);
              }
            )
          }
          logout() {

            this.http.get("/api/auth/logout").subscribe(
              res => {
                console.log(res);
              },
              (err: HttpErrorResponse) => {

                console.log(err.error);
                console.log(err.name);
                console.log(err.message);
                console.log(err.status);
              }
            );
          }
        }

Solution: Finally resolve by entry in proxy.config.json given below "pathRewrite": {"^/api" : ""} so final json file is

{
    "/api/*":{

        "target":"http://10.104.40.14:8290/my_app",
        "secure":false,
        "pathRewrite": {"^/api" : ""}
    }
}
edkeveked

Try to write your post request this way:

login(username, password, rememberMe)) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    //You can append here whatever you like in your headers;
    headers.append(username, password);

    options: RequestOptions = new RequestOptions(headers);

    this.http.post(/api/security/login, options)
      .suscribe(res => res.json())
  }

The 401 is an error coming from the server handling the request. You need to see, if the server is getting the headers of your request or not.

Regarding your proxy config, you can do the following:

{ "/api": { "target": "yourUrl.com", 
             "secure": false, 
             "pathRewrite": {"^/api" : ""} 
          }
}

The pathRewrite option will remove api from your url.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Unable to make HttpClient post request in Angular because of CORS issue

How to POST JSON request using Apache HttpClient?

Angular CLI Proxy conf is not working for POST request

Http request to parse server using Angular HttpClient

Angular : Unable to GET local json using HttpClient

HTTPClient POST request not working on Angular 5 / Angular Universal

Angular HttpClient fails to proxy

How do you make a request with matrix parameters in the URI to a backend when using Angular's HttpClient?

HttpWebRequest to HttpClient post Request

How to send POST request via angular's HttpClient?

Angular 8 HttpClient Post Request Content-Type debacle

Getting response headers from HttpClient post request in Angular?

Angular 6 HTML response from HttpClient POST request

Why is my Angular 6 httpClient POST request firing twice

unable to send post request using urlrequest

Unable to retrieve page 2 using POST request

Unable to POST request using guzzle with the Amadeus API

how to properly make a POST request using Java Apache HttpClient?

Flutter Dart - How to send a Post Request using HttpClient()

How to POST NON-JSON request using Apache HttpClient?

config proxy in angular cli

Angular HttpClient - request not executed

How do I do a patch request using HttpClient in dotnet core?

Angular HttpClient not executing with post

Angular HttpClient post not sending

Angular HttpClient post not working

Do something after a DELETE request is complete with Angular HttpClient

Sending a post request behind a proxy server using idHTTP

angular4: unable to obtain response string using httpclient get