如何使用Android AsyncHttpClient发送HTTP POST参数?

时间:2014-12-15 19:55:59

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

我正在尝试用于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库是否已损坏,或者我在哪一方做错了什么?

1 个答案:

答案 0 :(得分:2)

您可能错过了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())