我正在创建一个应用程序,它使用一些 node.js 脚本来编写服务器脚本,主要是因为 node.js 有 Firebase
支持,但由于某种原因我无法在我的请求中发送任何参数(两者获取和发布)。
我的android代码如下
private void sendData(final String name){
StringRequest sr = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(),response.toString()+" returned from node.js server",Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString()+"The Server returned error",Toast.LENGTH_SHORT).show();
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String,String> map = new HashMap<>();
map.put("test",name);
return map;
}
};
RequestQueue r = Volley.newRequestQueue(getApplicationContext());
r.add(sr);
}
对应的node.js脚本如下
app.get('/hello', function(request, response){
var outputJson = request.params.test;
response.send(JSON.stringify(outputJson));
console.log(outputJson);
})
出于某种原因,控制台总是记录 undefined。遵循 this post 的建议我还尝试将数据包含在请求正文中,并通过 request.body.test
从 node.js 中的请求获取数据。
我想知道出了什么问题,最重要的是我还想知道如何接收和处理 POST
请求。我在一些博客上读到我必须实现某种中间件
。在该领域的一些澄清也将不胜感激。
最佳答案
我查看了您的代码,发现 Android
代码中存在一些缺陷。
HashMap 是在
getHeaders()
函数中定义的,但实际上应该像这样在getParams()
中定义@Override public Map<String, String> getParams() throws AuthFailureError { HashMap<String,String> map = new HashMap<>(); map.put("test",name); return map; }
- 与其尝试通过
request.params
检索数据,不如尝试使用request.body
。
关于javascript - 参数未使用 Volley 从 android 发送到 node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662056/