0

I want to check if an HTTP request came from a phone or a pc so that I know what HTML file to send back. How do I do that? I am using express. Here is my code for my nodeJS server:

var express = require("express"); 
var fs = require("fs"); 

var server = express(); 

server.use("/Static", express.static('./Static/'));

server.get("/", (req, res) => {
    res.send(fs.readFileSync("./main.html", "utf8")); 
}); 

server.listen(8001);
Jason Yang
  • 37
  • 6
  • Not updated for years, but maybe worth a look: [express-device](https://www.npmjs.com/package/express-device) – pzaenger Jan 19 '20 at 22:20
  • 1
    I'd suggest you do some reading on "responsive design". The general idea is that you use CSS media queries to control the formatting based on screen size and orientation and you don't trying to detect phone or not and render different HTML based on that binary decision. Then, you can handle anything from a small phone screen, to a large phone screen to a tablet to a small laptop to a large laptop to a small desktop to a large desktop and do some intelligent based on the available size. – jfriend00 Jan 19 '20 at 22:34
  • Possible [duplicate](https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device). You've set up your express server but you still don't know the clients device. So you should get the client's device using [this](https://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device) and use it as a header to all of your request. – Karma Blackshaw Jan 20 '20 at 02:25

2 Answers2

1

You can check it by reading User Agent request headers, like following

function testDevice(req, res) {
  console.log(req.headers)

  if (req.header('user-agent').indexOf('Mobile') != -1) {
      console.log('You are using mobile device');
    } else {
      console.log('this is probably a computer');
    }
}

You will get different values for User Agent header from PC and Mobile.

  1. For PC you will get something like this:
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
  1. For Mobile you will get something like this:
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
Sandip Nirmal
  • 1,760
  • 14
  • 22
0

I found this module which is bit use full. PFB sample code.

var express = require('express');
var app = express();
var device = require('express-device');
app.use(device.capture());

app.get('/hello',function(req,res) {
    console.log(req.device);
    res.send("Hi to "+req.device.type.toUpperCase()+" User");
});

app.listen(3000);
console.log("Listening to Port 3000");
PKInd007
  • 368
  • 2
  • 7