2

I have below get request. But its giving 401 Unauthorized error.

var headers = new Headers();
        headers.append('Content-Type': 'application/json;charset=UTF-8');

        this.http.get(urgentPostURL + encodeURIComponent(this.urgentpost.comment))
        .map((res:Response) => res.json())
        .subscribe(data => { 

          this.result = data;
          console.log('UrgentPost Result : ' + this.result.Success);

          if (this.result.Success == true) {
              console.log("SUCESSS");
          } else {
              console.log("FAILED");
          }

        },err => console.error(err),() => console.log('done'));

What I'm doing wrong here?

Edited

After updated to the following code I'm still getting 401:

var headers = new Headers();
        headers.append('Content-Type': 'application/json;charset=UTF-8');
        headers.append('Authorization', 'Basic ' + btoa("123" + ':' + "123"));
        this.http.get(urgentPostURL + encodeURIComponent(this.urgentpost.comment), { headers: headers })
        .map((res:Response) => res.json())
        .subscribe(data => {

General:

Request Method:GET
Status Code:401 Unauthorized

Response headers:

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:0
Date:Tue, 23 Feb 2016 11:26:17 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/8.0
Set-Cookie:ARRAffinity=6e6dd0608a0902ef40a800ab07ee37397d7b6cfbd85cf3dea254a7115d365bc1;Path=/;Domain=sd.sddd.net
WWW-Authenticate:Basic
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

Request headers:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic MDAwMDAwMDoxMjM0NTY3OA==
Connection:keep-alive
Content-Type:application/json;charset=UTF-8
Host:sd.sddd.net
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36
halfer
  • 19,824
  • 17
  • 99
  • 186
happycoder
  • 927
  • 3
  • 13
  • 28

1 Answers1

3

I seems that the server requires authentication. You didn't define the Authorization header for your call.

Here is a sample for an HTTP basic authentication:

var headers = new Headers();
headers.append('Content-Type': 'application/json;charset=UTF-8');
headers.append('Authorizcation', 'Basic '+btoa(username + ':' + password));

this.http.get(urgentPostURL + encodeURIComponent(
          this.urgentpost.comment,
          { headers: headers })
    .map((res:Response) => res.json())
    (...)

Don't forget to specify your headers for your request and to import the Headers class.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thank you Thierry. I've got successful status (200k) but it throws this error. "XMLHttpRequest cannot load 'my_url'. Request header field Authorizcation is not allowed by Access-Control-Allow-Headers in preflight response". and these are my imports: import 'rxjs/add/operator/map'; import { Http, Headers } from 'angular2/http'; – happycoder Feb 23 '16 at 10:42
  • Great! What do you have in the `Access-Control-Allow-Headers`? Does the response of the preflighted request (the OPTIONS request) contain `Access-Control-Allow-Credentials: true`? – Thierry Templier Feb 23 '16 at 10:51
  • See this answer: http://stackoverflow.com/questions/34916623/angular2-http-request-not-able-to-add-headers/34917039#34917039 – Thierry Templier Feb 23 '16 at 10:52
  • Yes, response has Access-Control-Allow-Credentials: true. – happycoder Feb 23 '16 at 11:00
  • This is a part of my response: Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:Authorization, Origin, X-Requested-With, Content-Type, Accept Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-Origin:* Content-Length:0 – happycoder Feb 23 '16 at 11:04
  • I see this in your error message `"field Authorizcation is not allowed by Access-Control-Allow-Headers"`. `Authorizcation` should be `Authorization`... – Thierry Templier Feb 23 '16 at 11:07
  • I updated my question. It again gives 401. I cannot think of what I'm missing here. – happycoder Feb 23 '16 at 11:37
  • Are you sure that you server uses HTTP basic auth? Do the provided credentials allow you to authenticated on the server side? I mean: is it a valid username / password? – Thierry Templier Feb 23 '16 at 11:42
  • Yes, actually below is the code snippet I need to convert. $http.get(serviceURL + 'Urgent?messageContent=' + encodeURIComponent($scope.messageContent)). success(function (data, status, headers, config) {.. Earlier I have used this code and worked fine. – happycoder Feb 23 '16 at 11:51
  • I would leverage the `URLSearchParams` class for query parameters: URLSearchParams search = new URLSearchParams(); search.set('messageContent', messageContent); this.http.get(serviceURL + 'Urgent', { headers: headers, search: search }) – Thierry Templier Feb 23 '16 at 11:54
  • var headers = new Headers(); headers.append('Content-Type': 'application/json;charset=UTF-8'); headers.append('Authorization', 'Basic ' + btoa("123" + ':' + "123")); URLSearchParams search = new URLSearchParams(); search.set('messageContent', this.urgentpost.comment); this.http.get(SERVER_URL + 'Urgent', { headers: headers, search: search }).. but No luck Thierry. Same error. Thank you very much for your time. Let me try this little bit and I will comment the status tomorrow. – happycoder Feb 23 '16 at 12:16
  • Hi Thierry, finally I solved it out. Thanks alot. I marked your answer as correct. I needed to add appname for authorization headers. You helped me alot in this :) Thank you. – happycoder Feb 24 '16 at 08:19
  • Without setting it always cannot I do this in Angular 2.document.execCommand("ClearAuthenticationCache"); var encoded = Base64.encode($scope.username + ':' + $scope.password + ':' + appName); $http.defaults.headers.common.Authorization = 'Basic ' + encoded; – happycoder Feb 24 '16 at 09:10
  • You're welcome! I think this question could help you: http://stackoverflow.com/questions/35375530/how-do-i-add-a-json-web-token-to-each-header/35377964#35377964. – Thierry Templier Feb 24 '16 at 09:14