【问题标题】:Angular2 http POST request failingAngular2 http POST 请求失败
【发布时间】:2017-03-06 05:07:40
【问题描述】:

我的服务有两种方法 Get 和 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);
} 

获取:

发帖:

我在使用 Post 方法时做错了什么?我有来自我的 angular1 应用程序的原始代码:

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

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

【问题讨论】:

    标签: angular django-rest-framework ionic2


    【解决方案1】:

    angular的Http.post方法的第二个参数不是请求选项,而是post请求的正文。

    因此,您应该更改调用,将请求选项作为第三个参数传递给 http.post,而不是第二个。

    例如:

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

    see the Angular docs

    【讨论】:

    • 如何修改我的请求? return this.http.post(this.base_url + 'save_progress/' + exerciseId + "/" + value + "/", body:any, options) 喜欢这样吗?
    • return this.http.post(this.base_url + 'save_progress/' + exerciseId + "/" + value + "/", {}, options) 会起作用。只需将一个空对象作为您的第二个参数,因为您没有任何内容可在正文中发布
    猜你喜欢
    • 2016-09-07
    • 1970-01-01
    • 2016-05-14
    • 2017-03-12
    • 1970-01-01
    • 2017-03-10
    • 2012-04-08
    • 1970-01-01
    • 2017-10-07
    相关资源
    最近更新 更多