Dimuthu
Dimuthu

Reputation: 409

Angular 2 -POST 401 Unauthorized

I am using angular 2. I want to post data using API, but I get unauthorized access error...

Can someone help me figure out why am I getting this error?

401 Unauthorized

Upvotes: 1

Views: 1475

Answers (3)

Kavinda Senarathne
Kavinda Senarathne

Reputation: 2004

Check with the headers you configured for Authorization in service.ts file. If it's not you need to add the headers to the URL.

Headers can be used as

const httpOptions = {
    headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('token')
    })
} 

And add this to the URL as follows. As and example:

getUsers() {
    return this.http.get(this.baseUrl + 'users', httpOptions);
}

Upvotes: 6

kautikmistry
kautikmistry

Reputation: 746

Your problem is missing or wrong content type header.

For post method requests your content type should be one of the standard form types: application/x-www-form-urlencoded or multipart/form-data

Upvotes: 2

Eli
Eli

Reputation: 1846

Check your API authentication scheme. you might need to login first ( if using cookies ). Or provide some authentication header.

Upvotes: 2

Related Questions