Reputation: 97
I want to serve my static files "web.html" and "mobile.html", but send them only if the user is connected from the web/mobile.
i thought that this the code that does this:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/public', {index: false}));
app.get('/', function (req, res) {
console.log("user connected");
if (req.headers['user-agent'].match('mobile')) {
res.sendFile(__dirname + '/public/mobile.html');
} else {
res.sendFile(__dirname + '/public/web.html');
}
});
but this code doesn't work. from what i understood the express.static will only serve index.html when requesting '/'. is there a way to serve a specific file when requesting '/' ?
Thanks!
Upvotes: 1
Views: 1202
Reputation: 95
<script src="/scripts/script.js"></script>
Use the above line in the index file or the HTML file.
var app=express();
app.use(express.static(__dirname + '/assets'));
Use this in the app.js or the starting point of your node js application. Create an assets folder at the root level. Inside assets folder there are sub folders : Images, CSS and Scripts
Upvotes: 1
Reputation: 27282
Your basic logic is correct; the problem is with your mobile detection. In many mobile browsers (I just tried this on iPhone), the UA string has "Mobile" (with a capital "M"), and you're matching on a lowercase. I changed this to:
if (req.headers['user-agent'].match(/\bmob/i)) {
/\bmob/i
is what I usually use for mobile detection; I've found it to be really solid. A better choice might be @user3229720's answer, which prevents you from having to worry about the messy details of UA parsing, but I thought you might want to know in more detail what's going on here.
Upvotes: 1
Reputation: 941
Check express-device out. It accomplishes what I think you are trying to do (making a mobile version and a desktop version).
Upvotes: 0