网站建设通常包括前端和后端的代码。以下是一个简单的示例,使用 HTML/CSS/JavaScript 作为前端,以及 Node.js 和 Express 作为后端。
前端代码
HTML (index.html)
html
CSS (styles.css)
css
body {
font-family: Arial, sans-serif;
}
header {
background-color: #4CAF50;
color: white;
padding: 1em;
text-align: center;
}
main {
padding: 20px;
}
input[type="text"] {
padding: 10px;
margin: 10px 0;
}
button {
padding: 10px 15px;
}
JavaScript (script.js)
javascript
document.getElementById('dataForm').addEventListener('submit', function (event) {
event.preventDefault();
const name = document.getElementById('name').value;
fetch('/submit', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name })
})
.then(response => response.json())
.then(data => {
document.getElementById('response').innerText = data.message;
});
});
后端代码
Node.js + Express (server.js)
javascript
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public')); // 提供静态文件
app.post('/submit', (req, res) => {
const { name } = req.body;
res.json({ message: `你好, ${name}! 感谢你的提交.` });
});
app.listen(PORT, () => {
console.log(`服务器正在运行在 http://localhost:${PORT}`);
});
项目结构
/your-project
│
├── public
│ ├── index.html
│ ├── styles.css
│ └── script.js
└── server.js
运行代码
1. 先安装 Node.js 和 Express:
bash
npm init -y
npm install express body-parser cors
2. 将以上代码分别放入相应的文件中。
3. 启动服务器:
bash
node server.js
4. 在浏览器中打开 `http://localhost:3000` 查看网站。
这是一个非常基础的网站示例,可以根据需要进行扩展和修改。
查看详情
查看详情