简体   繁体   English

Angular2 HTTP POST请求失败

[英]Angular2 http POST request failing

My service has two methods Get and Post. 我的服务有两种获取和发布方法。 Get request is working but post request fails saying not authorized. 获取请求有效,但发布请求失败,提示未授权。

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);
} 

Get: 得到:

在此处输入图片说明

Post: 发布:

在此处输入图片说明

What am I doing wrong with Post method? Post方法有什么问题? I have original code from my angular1 application which works: 我从我的angular1应用程序中获得了原始代码,该代码可以正常工作:

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

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

The second parameter to angular's Http.post method is not the request options, but rather the body of the post request. angular的Http.post方法的第二个参数不是请求选项,而是发布请求的正文。

So, you should change your call to pass your request options as the third parameter to http.post, not the second. 因此,您应该更改呼叫以将请求选项作为第三个参数传递给http.post,而不是第二个。

eg: 例如:

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

see the Angular docs 查看Angular文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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