1 year ago
#153341
BrijeshSinghal
How to serve different files based on screen size with Express?
I'm trying to create an adaptive express server. Basically, whatever request it is, insert a screen type in the url and process the request again.
// bring in express
const express = require("express");
// bring in express handlebars
const exphbs = require("express-handlebars");
// initialise express with the epxress class constructor
const app = express();
// bring in path
const path = require("path");
// middleware logger
const logger = require("./middleware/logger");
app.use(logger);
// importing routes
const desktop = require("./routes/desktop");
const tablet = require("./routes/tablet");
const phone = require("./routes/phone");
const { nextTick } = require("process");
// set view engine to express handlebars
app.engine("handlebars", exphbs.engine());
app.set("view engine", "handlebars");
// screenvalidation get request
app.get(`/`, (req, res, next) => {
res.sendFile(path.join(__dirname, "public", "screenValidation.html"));
});
// set static folder (home dir for requests)
app.use(express.static(path.join(__dirname, "public")));
// route phone
app.use("/phone", phone);
// route tablet
app.use("/tablet", tablet);
// route desktop
app.use("/desktop", desktop);
// port
const PORT = 80;
app.listen(PORT, () => console.log(`server started on ${PORT}`));
This is my app.js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Screen Validation</title>
</head>
<body>
<script>
const w = screen.width;
const h = screen.height;
if(w <= 414 && h <= 896) {
// phone
window.location.replace(`${window.location.origin}/phone${window.location.pathname}`);
} else if (w <= 1280 && h <= 800) {
// tablet
window.location.replace(`${window.location.origin}/tablet${window.location.pathname}`);
} else {
// desktop
window.location.replace(`${window.location.origin}/desktop${window.location.pathname}`);
}
</script>
</body>
</html>
This is my screen validation file/script. I'm trying to send a different file depending on screen size. However, this script I think is recursive. How do I get it to run only once per request? or is there a better way to do this? Please help me out, thanks.
node.js
express
web-development-server
adaptive-design
0 Answers
Your Answer