一、端口号的含义
1、端口号的作用
端口号是用于标识主机中特定进程的数字,分配给客户端或服务端的进程。对于HTTP而言,端口号默认为80。而我们所熟知的127.0.0.1:8080,则是本机IP地址(回送地址),加上其它服务程序所占用的端口号8080。
2、示例代码:
const http = require('http');
const hostname = '127.0.0.1';
const port = 8080;
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
二、回送地址的使用
1、回送地址的作用
回送地址,即127.0.0.1,其作用是将网络数据包返回给发包者的地址。可以通过回送地址实现在本机进行服务端程序测试,以及在一个没有独立IP地址的计算机上测试客户端程序。
2、示例代码:
const http = require('http');
const hostname = '127.0.0.1';
const port = 8080;
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
三、HTTP协议的特点
1、HTTP协议的无状态性
HTTP协议是无状态的,即两次请求之间没有关联。这样一来,服务端无法知道现在请求与上次请求是否来自同一个客户端。可以通过Cookie、Session等机制实现服务端记录客户端信息。
2、HTTP协议的请求方式
HTTP协议的请求方式有GET、POST、PUT、DELETE等。GET方式用于获取资源,POST方式用于提交资源,PUT方式用于更新资源,DELETE方式用于删除资源。
3、示例代码:
const http = require('http');
const hostname = '127.0.0.1';
const port = 8080;
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
if(req.method === 'GET') {
res.end('This is a GET request!');
} else if(req.method === 'POST') {
res.end('This is a POST request!');
} else {
res.end('This is not a GET or POST request!');
}
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
四、路由的概念与应用
1、路由的含义
路由是指为了实现不同URL地址请求的分发而设立的一种机制。在Node.js中,使用路由实现对不同请求的不同响应。这样一来,就可以实现实现更加灵活的请求页面响应。
2、示例代码:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 8080;
const route = {
'/': function(req, res) {
res.end('This is the home page');
},
'/about': function(req, res) {
res.end('This is the about page');
},
'/contact': function(req, res) {
res.end('This is the contact page');
}
};
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
let pathname = url.parse(req.url).pathname;
if(route[pathname]){
route[pathname](req, res);
} else {
res.end('404 Page Not Found');
}
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
五、模板引擎的使用
1、模板引擎的作用
模板引擎是指以标签或代码为基础,结合数据渲染生成具有结构、样式和功能的HTML页面的工具。在Node.js中,常用的模板引擎有handlebars和ejs。
2、示例代码(使用ejs):
const http = require('http');
const ejs = require('ejs');
const hostname = '127.0.0.1';
const port = 8080;
const tpl = `
Content:
`;
http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
const data = {
title: 'EJS Demo',
heading: 'Hello EJS',
content: 'This is an example of using EJS!'
};
const html = ejs.render(tpl, data);
res.end(html);
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/159320.html
微信扫一扫
支付宝扫一扫