How can you develop a simple website using node.js as the backend and HTML/CSS as the front-end?
Developing a simple website using Node.js for the backend and HTML/CSS for the front-end involves several steps. Below is a basic guide to get you started:
Step 1: Set Up Your Project
Install Node.js:
Create a Project Folder:
- Create a new folder for your project.
Initialize a Node.js Project:
Step 2: Create Backend with Node.js
Install Express:
Create
app.js
(orindex.js
):Set up a basic Express server:
javascriptCopy codeconst express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server listening at http://localhost:${port}`); });
Run Your Server:
Execute your Node.js server:
bashCopy codenode app.js
Step 3: Create Frontend with HTML/CSS
Create
p
ublic
Folder:Create HTML and CSS Files:
Example index.html
:
htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css">
<title>Node.js Website</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
</body>
</html>
Example style.css
:
cssCopy codebody {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
text-align: center;
padding: 20px;
}
h1 {
color: #333;
}
Step 4: Serve Static Files with Express
javascriptCopy codeconst express = require('express');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});