【问题标题】:req.user undefined for request from Android app to NodeJS serverreq.user 未定义从 Android 应用程序到 NodeJS 服务器的请求
【发布时间】:2017-03-18 06:58:05
【问题描述】:

我正在开发一个带有 NodeJS 后端服务器的 Android 应用程序。当用户登录后向不同页面发出请求时,我在验证用户时遇到问题。

登录后,我将set-cookie 值存储在SharedPrefs 中。现在,当我发出 POST 请求时,我在标头中发送 set-cookie 值,即 con.setRequestProperty("set-cookie", cookie); 用于使用 req.user.authenticate 在后端验证用户。

但是,req.user 未定义,因此请求失败。这里有什么问题?谢谢。

下面是我的 POST 请求代码。

    con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "\"Mozilla/5.0\"");

    con.setDoOutput(true);

    JSONObject jsonParam = new JSONObject();
    try {
        jsonObject.accumulate("set-cookie", cookie);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    OutputStreamWriter out = new   OutputStreamWriter(con.getOutputStream());
    out.write(jsonParam.toString());
    out.close();

    int responseCode = con.getResponseCode();
    System.out.println("Response Code:"+responseCode);

【问题讨论】:

    标签: android node.js http-post session-cookies


    【解决方案1】:

    以这种格式发送数据

     String data = "";
    
    InputStream inputStream = null;
    
    
    try{
    
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("set-cookie", cookie);
    
    
        data = jsonObject.toString();
        Log.d("json data",data);
        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
    
        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
        StringEntity se = new StringEntity(data);
    
        // 6. set httpPost Entity
        httpPost.setEntity(se);
    
        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
    
        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);
    
        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
    
        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    
    
        System.out.print(result);
    
    }catch (Exception e){
    
        e.printStackTrace();
    }
    

    【讨论】:

    • 不推荐使用 DefaultHttpClient() 吗?
    • 您使用 HttpURLConnection 以 json 格式发送数据很重要。但在发送之前将其转换为字符串
    • 尝试使用 HttpURLConnection 使其工作。发送 JSON 格式的数据时遇到问题。
    • 我仍然收到 req.user 的未定义错误。用新代码更新了我的问题
    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2019-08-13
    • 1970-01-01
    • 2015-09-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多