2017-03-05 191 views
0

我的服务有两个方法Get和Post。获取请求正在工作,但发布请求失败,说未经授权。Angular2 http POST请求失败

public getExercise(exerciseId): Observable<Exercise[]>{ 

    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers, withCredentials: true }); 

    return this.http.get(this.base_url + 'get_exercise/' + exerciseId + '/', options) 
    .map(this.extractData) 
    .catch(this.handleError); 
} 

public saveRating(value, exerciseId): Observable<Exercise[]>{ 

    console.log(value + " " + exerciseId) 

    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    headers.append('Authorization','Basic') 
    let options = new RequestOptions({ headers: headers, withCredentials: true }); 

    return this.http.post(this.base_url + 'save_progress/' + exerciseId + "/" + value + "/", options) 
    .map(this.extractData) 
    .catch(this.handleError); 
} 

得到:

enter image description here

帖子:

enter image description here

我在做什么毛病Post方法?我从angular1应用程序原代码的工作原理:

var url = "/api/exercises/save_progress/" + exerciseType + "/" + rating + "/"; 

       if($cookies.token){ 
        $http.defaults.headers.common.Authorization = 'Token ' + $cookies.token; 
       } 

回答

2

的第二个参数角的Http.post方法不是请求选项,而是发布请求的主体。

所以,你应该改变你的请求,把你的请求选项作为第三个参数传递给http.post,而不是第二个参数。

如:

return this.http.post(this.base_url + 'save_progress/' + exerciseId + "/" + value + "/", {}, options) 

see the Angular docs

+0

如何修改,然后我的要求? '返回this.http.post(this.base_url +'save_progress /'+ exerciseId +“/”+ value +“/”,body:any,options)'这样吗? – Nitish

+0

return this.http.post(this.base_url +'save_progress /'+ exerciseId +“/”+ value +“/”,{},options)会起作用。只是有一个空的物体作为你的第二个参数,因为你没有任何东西在主体中发布 – snorkpete

+0

是的,它的工作!感谢您指出。 – Nitish