user782400 user782400 - 1 month ago 9
Node.js Question

req.user undefined for request from Android app to NodeJS server

I am developing an Android app with a NodeJS backend server. I am having problems authenticating the users when requests are made to different pages after the user is logged in.

Once I log in, i store the

set-cookie
value in
SharedPrefs
. Now when I make a POST request, I am sending the
set-cookie
value in the header, i.e.
con.setRequestProperty("set-cookie", cookie);
for authenticating the user on the backend using
req.user.authenticate
.

However,
req.user
is undefined and hence the request fails. What could be wrong over here? Thanks.

Below is my POST request code.

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);

Answer

Send data in this format

 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();
}