【问题标题】:How to send HTTP POST parameters using Android AsyncHttpClient?如何使用 Android AsyncHttpClient 发送 HTTP POST 参数?
【发布时间】:2014-12-15 19:55:58
【问题描述】:

我正在尝试适用于 Android 的 AsyncHttpClient 库,并尝试使用它向我的 Express (NodeJS) 服务器发出 HTTP POST,但在将参数附加到 POST 请求时遇到了困难。

这就是我的工作:

AsyncHttpClient httpClient = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("username", usernameEditText.getText().toString());
requestParams.put("password", passwordEditText.getText().toString());
httpClient.post("http://1.2.3.4/sign-up", requestParams, new JsonHttpResponseHandler() {
    // here I override the onSuccess and onFailure methods
}

但是当请求到达 Express 服务器时,我在任何地方都找不到参数。我习惯于在req.body中查找POST参数,但是:

app.post('/sign-up', function(req, res) {
  var username = req.body.username; // throws error because req.body is undefined
});

AsyncHttpClient 库是否损坏或我在任一方面都做错了什么?

【问题讨论】:

  • 嗯,似乎 Express 服务器可能有问题,因为如果我使用 curl 在那里发送 POST 请求,也会发生同样的事情。如果我发现了什么,我会自己调查并发布答案。

标签: android node.js express http-post android-async-http


【解决方案1】:

您可能缺少 body-parser 中间件。

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

【讨论】:

  • 是的,你当然是对的。但是,我想知道他们为什么将其从 Express 本身中删除。我知道它有它的问题,但是如果没有这个,POST 请求不是没有用吗?
  • 并不是所有的http服务器都需要处理post请求。
  • 是的,我知道。我的观点是,为什么在没有body-parser 的情况下甚至可以做app.post,因为它无论如何都不能正常工作?没关系。
  • 它可以在没有 body-parser 的情况下工作。而且您始终可以自己解析帖子内容或使用不同的模块。 github.com/felixge/node-formidable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 2016-06-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
相关资源
最近更新 更多