1

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" : ""}
    }
}
Rahul Kumar Jain
  • 103
  • 4
  • 13
  • Could you use the developer tools in your browser and see if your requests are issued? You can see if your post request contains the headers you passed to it. – edkeveked Oct 24 '17 at 14:42
  • Request URL:http://localhost:4200/api/security/login Request Method:POST Status Code:401 Unauthorized Remote Address:127.0.0.1:4200 Referrer Policy:no-referrer-when-downgrade Response Headers view source Access-Control-Allow-Origin:* cache-control:must-revalidate,no-cache,no-store connection:close content-type:text/html;charset=iso-8859-1 date:Tue, 24 Oct 2017 15:01:27 GMT Transfer-Encoding:chunked www-authenticate:Bearer x-application-context:application:production:8290 X-Powered-By:Express – Rahul Kumar Jain Oct 24 '17 at 15:26
  • Request Headers view source Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, br Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:61 Content-Type:text/plain X-Requested-With:XMLHttpRequest Request Payload view source {username: "admin@example.com", password: "a123456"} password : "a123456" username : "admin@example.com" Name – Rahul Kumar Jain Oct 24 '17 at 15:27
  • when I hit the get request it is giving proper response but not sure why post is creating an issue – Rahul Kumar Jain Oct 24 '17 at 15:28
  • It might be related to how the header of your post is formatted – edkeveked Oct 24 '17 at 15:38

1 Answers1

1

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.

edkeveked
  • 17,989
  • 10
  • 55
  • 93
  • i am using httpClient so need to pass payload as username and password and header as const headers = new HttpHeaders({ 'X-Requested-With' :'XMLHttpRequest' }); along with content-type. how to set mutliple header attributes – Rahul Kumar Jain Oct 24 '17 at 15:34
  • this is the angular 1 request header equest URL:http://localhost:5002/auth/login Request Method:POST Status Code:200 OK Remote Address:[::1]:5002 Referrer Policy:no-referrer-when-downgrade – Rahul Kumar Jain Oct 24 '17 at 15:40
  • Using the `RequestOptions` you can specify `{ 'X-Requested-With' :'XMLHttpRequest' } ` on your request. I edited my answer. – edkeveked Oct 24 '17 at 15:53
  • [ts] Type 'Headers' has no properties in common with type 'RequestOptionsArgs'. const headers: Headers – Rahul Kumar Jain Oct 25 '17 at 05:07
  • 1
    I edited the question based on this [post](https://stackoverflow.com/questions/44728775/type-headers-has-no-properties-in-common-with-type-requestoptionsargs) – edkeveked Oct 25 '17 at 05:57
  • thanks just saved me. i was hitting request using proxy.config.json and hence it was giving 401 authorization error I just tried without it and it was working fine. also setting header is not required,could you please suggest how to manage proxy using proxy.config.json in angular-cli – Rahul Kumar Jain Oct 25 '17 at 10:44
  • finally got success with this { "/api": { "target": "http://url.com", "secure": false, "pathRewrite": {"^/api" : ""} } } – Rahul Kumar Jain Oct 25 '17 at 10:49
  • Great, you succeeded! I updated my answer. You can upvote and accept it. – edkeveked Oct 25 '17 at 13:45
  • hi after changing my webpack server port from 4200 to 5003 my api call again stop working and now getting 401 Unauthorization error and if i revert back port to 4200 it works fine – Rahul Kumar Jain Nov 01 '17 at 09:20
  • 1
    @RahulKumarJain, you can open a new SO ticket for it – edkeveked Nov 01 '17 at 09:25