【发布时间】:2017-02-28 05:05:03
【问题描述】:
我花了比我想承认的更多的时间来找到这个问题的答案,但我自己似乎无法弄清楚。 我在this tutorial 之后有一个 Django-rest-api,可以使用 httpie 或 curl 与 api 通信并传递凭据。我还有一个 angular 2 SPA,它可以发送 http.get 请求并从服务器取回数据。一切正常,直到我尝试使用 POST 并从 angular 2 应用程序中传递身份验证数据,导致 Http 403(禁止)。
由于 api 可以很好地与 curl 配合使用,这让我觉得我在以角度发送 http.post 时做错了。这是我的代码:
postStuff() {
var body = "username=myusername&password=mypassword";
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://localhost:8000/rest/', body, { headers: headers })
.map(res => res.json());
}
这是一个运行良好的 curl 示例:
curl -H 'Accept: application/json; indent=4' -u myusername:mypassword http://127.0.0.1:8000/rest/
我需要在标头中包含“授权”标头吗?我尝试了 Authorization:Basic 但没有运气。我还运行了一个 curl 以找到允许的选项并且允许 POST。 我基本上想要我的 http.post 中 curl 中的“-u 用户名:密码”(或 http.get,如果可能的话)的等效项
还值得一提的是,在不需要身份验证的 api 部分,我使用 POST 得到 400(错误请求),而 GET 工作正常。 例如,这很好用:
return this.http.get('http://127.0.0.1:8000/users/')
.map(res => res.json())
但事实并非如此:
return this.http.post('http://127.0.0.1:8000/users/', { headers: headers })
.map(res => res.json());
【问题讨论】:
标签: curl angular http-headers django-rest-framework