【问题标题】:Http post request in Angular2 does not pass parametersAngular2中的Http post请求不传递参数
【发布时间】:2016-12-31 03:15:46
【问题描述】:

我正在尝试使用 Angular2 POST 向我的 Python/Tornado 后端发送一个参数,该后端返回一个 JSON 对象。参数正在正确发送,但在 Python 端,它返回 400 POST missing arguments 错误。我在前端和 Python/Tornado 服务器中使用 Ionic 2/Angular2。

Angular2代码如下: 这里的内容是一个包含 HTML 表格的变量

let body = JSON.stringify({content: content});
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map(res => res.json()).subscribe(data => {
      console.log(data)
}, error => {
      console.log(JSON.stringify(error));
});

Python代码如下:

def post(self):
    print self.request.arguments
    print self.get_argument('content')
    self.finish(dict(result="ok", data=content))

这是错误:

[W 160824 06:04:30 web:1493] 400 POST /test (182.69.5.99): Missing argument content
[W 160824 06:04:30 web:1908] 400 POST /test (182.69.5.99) 1.67ms

【问题讨论】:

  • 你确定在你的js代码sn-p之前没有未定义内容吗?
  • 如果你这样做let body = JSON.stringify({content: content || ''}) 会怎样?

标签: json post angular typescript


【解决方案1】:

您也许应该尝试使用带有 URLencoded 内容类型的 URLSearchParams() 之类的东西。我对 Tornado 了解不多,但我使用的是 ASP 控制器,它运行良好。

请参阅 Angular2 文档:https://angular.io/docs/ts/latest/api/http/index/URLSearchParams-class.html

观看我正在使用的以下身份验证示例:

controllerURL: string = "/APIConnexion";

login(aLogin: string, aMdp: string) {
        // parameters definition (has to have the same name on the controller)
        let params = new URLSearchParams();
        params.set("aLogin", aLogin);
        params.set("aMdp", aMdp);
        // setup http request
        let lHttpRequestBody = params.toString();
        let lControllerAction: string = "/connexion";
        let lControllerFullURL: string = this.controllerURL + lControllerAction;
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers });

        // call http
        return this.http.post(lControllerFullURL, lHttpRequestBody, options)
            .map((res: any) => {
                // data received as JSON
                let data = res.json();

                // Do something with your data

            }
            ).catch(this.handleError);
    }

【讨论】:

    【解决方案2】:

    您的 Angular2 代码看起来很合理,但是您的 Python 代码是错误的,因为您将请求视为 x-www-form-urlencoded。您必须通过 request.body 属性访问 JSON 字符串:

    data = tornado.escape.json_decode(self.request.body)
    

    有关类似问题的答案,请参阅 https://stackoverflow.com/a/28140966/2380400

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2016-05-14
      • 2013-08-09
      • 1970-01-01
      • 2016-01-25
      • 2017-12-24
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多