简体   繁体   中英

401 Unauthorized error for GET request in Ionic 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM