DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>待办列表title>
head>
<body>
<h1>待办列表h1>
<form method="post" action="/">
<p><input type="text" name="item" />p>
<p><input type="submit" value="添加" />p>
form>
<ul><li>%li>ul>
body>
html>
const http = require('http')
const hostname = '127.0.0.1'
const port = 3000
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello World\n')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
F:\Github\Nodejs>node server.js
Server running at http://127.0.0.1:3000/
如何在服务器中加载模板页面?
F:\Github\Nodejs>node
Welcome to Node.js v18.12.1.
Type ".help" for more information.
> require('fs').readFile('server.js', (err, data) => {console.log(data);})
undefined
> ... 289 more bytes>
修改 server.js,增加加载静态页面的逻辑,代码如下
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: resource not found.');
response.end();
}
function readFile(response, filePath) {
fs.readFile(filePath, (err, data) => {
if (err) {
return send404(response);
}
var html = data.toString();
html = html.replace('%', [1,2,3].join('- '
));
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(html);
});
}
const server = http.createServer((request, response) => {
var absPath = './' + 'public/index.html';
readFile(response, absPath);
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})
执行 node server.js
F:\Github\Nodejs\todolist>node server.js
Server running at http://127.0.0.1:3000/
静态页面的%被替换成了列表1 2 3