I made a native android app client and a web app client for a node.js application. the android app client only receive the json response while the web app client receives the html response.So it is important for the node.js server to distinguish the request from android app and web app. I tried to use the http header Accept to distinguish the different requests. If the Accept header is application/json, then server can tell the request is from android, if the Accept header is html/text, then server can tell the request is from the web app
here is the web app client using form to send the request
<div class="input">
<input id="id_username" type="text" name="username" maxlength="75" />
</div>
<div class="input">
<input type="password" name="password" id="id_password" />
</div>
<input type="submit" value="Log in" class="btn btn-green"/>
</form>
here is the android client to send the http request
HttpPost post = new HttpPost(getURL);
post.setHeader("Accept", "application/json;q=0.9,*/*;q=0.8");
Both clients are ok, the problem is on the node.js server.
if(req.accepts('text/html')){
res.redirect('/login');
return;
}
else if(req.accepts('application/json')){
res.json({'msg':'user or password not valid'});
return;
}
The problem of this snippet is, even req.accepted is application/json, req.accepts('text/html') still equalls true.
I don't know why req.accepts('text/html') functions unexpectely
Look at Accept header you're sending from your android application:
post.setHeader("Accept", "application/json;q=0.9,*/*;q=0.8");
You have */*, which means that you're accepting everything, including text/html.
It'll work fine if you'll change your headers:
post.setHeader("Accept", "application/json");