使用Volley发送JsonObjectRequest POST请求时Node.js服务端无数据
我来帮你搞定这个问题!你遇到的情况是因为JsonObjectRequest的默认设计和你使用的方式不匹配,导致请求体格式与Content-Type不一致,Node.js的body-parser无法正确解析请求数据。
问题原因
JsonObjectRequest是Volley专门用来发送JSON格式请求体的类,它默认重写了getBodyContentType()方法,固定返回application/json; charset=utf-8。当你重写getParams()方法时,Volley会把参数编码成application/x-www-form-urlencoded格式的请求体,但请求头里的Content-Type还是application/json——这就造成了格式不匹配:
- Node.js的
bodyParser.json()会尝试把请求体解析成JSON,但实际是urlencoded字符串,解析失败 bodyParser.urlencoded()因为Content-Type不匹配,不会处理这个请求
最终req.body就变成了空对象{}。
而StringRequest默认的Content-Type就是application/x-www-form-urlencoded,所以重写getParams()时格式匹配,Node.js能正常解析。
解决方案
这里有两种可行的解决方式,你可以根据需求选择:
方案1:发送JSON格式请求体(推荐,符合JsonObjectRequest的设计)
直接构造JSONObject作为请求体传入JsonObjectRequest的构造函数,这样Volley会自动发送JSON格式的数据,Node.js的bodyParser.json()就能正确解析:
// 构造请求参数的JSON对象 JSONObject requestBody = new JSONObject(); try { requestBody.put("email", email.getText().toString()); // 如果有其他参数也可以在这里添加 } catch (JSONException e) { e.printStackTrace(); } JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, URL, requestBody, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理服务端返回的响应 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理请求错误 } }); queue.getInstance(getApplicationContext()).add(sr);
方案2:修改Content-Type适配urlencoded格式
如果你坚持要使用getParams()的方式,需要重写JsonObjectRequest的getBodyContentType()方法,让Content-Type和请求体格式匹配:
JsonObjectRequest sr = new JsonObjectRequest(Request.Method.POST, URL, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理响应 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误 } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String,String> params = new HashMap<>(); params.put("email", email.getText().toString()); return params; } // 重写该方法,设置正确的Content-Type @Override public String getBodyContentType() { return "application/x-www-form-urlencoded; charset=UTF-8"; } }; queue.getInstance(getApplicationContext()).add(sr);
这两种方式都能让你的Node.js服务端正确接收到email参数,测试一下就可以看到console.log(req.body)会输出{ email: "你输入的邮箱地址" }了。
内容的提问来源于stack exchange,提问作者Shahin Ghasemi

