初学nodejs,记录一下用http模块实现浏览器输入地址到收到本地服务器的html文件。
步骤:
- 创建本地服务器js文件
- 创建主页html文件
- 在浏览器上输入地址
本来想直接测试http的form提交。但是进行了跳转。
然后用ajax避免跳转,但是又涉及同源。
所以就用服务器返回html文件的方式。
只记录最重要的第一步:创建服务器js文件
const Http = require('http');//引用http模块。其继承了net模块。
const fs = require('fs');//引用文件系统模块
const client = Http.createServer((req, res) => {
if (req.method == 'GET') {
if (req.url == '/') {
console.log('get index.html');
res.setHeader('content-type', 'text/html');//application/html会下载文件
res.on('close',()=>{
console.log('send file close');
})
fs.createReadStream('index.html').pipe(res);//此处完成的时候,隐式调用了res.end();
}
}
});
client.listen(2333, 'localhost', () => {
console.log('client server build');
})
其中有用到pipe功能。感觉像是调用了res的write功能,第三个参数是callback。可能完成后的那个callback是end函数。所以就不需要在后面写end了。写了就错了。