httpangularionic2basic-authenticationwp-api

Ionic 2 WP-REST API post request 401 error with headers set for basic authentication


I am developing a simple application to create a post in Wordpress through wp-rest api. Everything(creating, updating deleting posts) works fine on postman. I can even fetch posts using same api in my application. but when I try to create a posts it shows 401 Unauthorised error in console. heres is my code for request.

//create post by api
createPost(title,content){
    var headers = new Headers();
    headers.append('Authorization', 'Basic '+btoa('tarun:iamtarun'));
    headers.append("Content-Type", "application/json");
    return this.http.post(this.postUrl+'?title='+title+'&content='+content , {
        headers:headers 
    })
    .map(res => res.json());
}

please help.


Solution

  • The structure of http post request is

    post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>;

    So the request should be,

    return this.http.post(this.postUrl+'?title='+title+'&content='+content ,{}, { headers:headers })
    

    Where the body is an empty object.