javascript - 参数未使用 Volley 从 android 发送到 node.js

标签 javascript android node.js express

我正在创建一个应用程序,它使用一些 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 代码中存在一些缺陷。

  1. HashMap 是在 getHeaders() 函数中定义的,但实际上应该像这样在 getParams() 中定义

     @Override
                public Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String,String> map = new HashMap<>();
                    map.put("test",name);
                    return map;
                }
    
  2. 与其尝试通过 request.params 检索数据,不如尝试使用 request.body

关于javascript - 参数未使用 Volley 从 android 发送到 node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662056/

相关文章:

node.js - 在 Strongloop 环回中重写关系远程方法

node.js - 当真正的 sequelize 连接在 require 树中时,为什么这个 sequelize-test-helper 调用不起作用?

java - 在 Java 中使用 DOM 解析器时出现 Null 异常

android - 未在路径 : DexPathList 上找到类 "com.apps.mobileapps.androidx"

javascript - 如何知道 Javascript 回调是同步的还是异步的?

javascript - 无法使用动态键更改 AngularJS 模型对象值

android - 了解包 X.Y.Z 是否正在 Android 中运行

node.js - 如何使用 mocha-phantomjs 测试 Node js 应用程序

javascript - 这是什么字符编码?

javascript - Google Analytics 链接帐户无法正常工作