1.创建http服务---在9000端口打开
// 1.导入http模块
const http = require('http');
// 2.创建服务对象
const server=http.createServer((request,response)=>{
response.end('hello world');
});
// 3.监听端口,启动服务
// (1.端口号,2.回调函数=》服务启动成功后的操作)
server.listen(9000,()=>{
console.log('服务启动成功');
});
使用node命令启动服务,以下是结果
使用‘Ctrl+C’停止端口服务
1.2 设置响应体格式--解决中文字符串乱码问题
使用setHeader方法设置utf-8,解决乱码问题
// 1.导入http模块
const http = require('http');
// 2.创建服务对象
const server=http.createServer((request,response)=>{
response.setHeader('Content-Type','text/html;charset=utf-8');
response.end('你好,NodeJS');
});
// 3.监听端口,启动服务
// (1.端口号,2.回调函数=》服务启动成功后的操作)
server.listen(9000,()=>{
console.log('服务启动成功');
});
结果
2.HTTP服务默认是80端口,也可以用1.的方法指定端口进行访问
常用端口为:3000 8080 9000
3. 浏览器查看HTTP报文
仍然是1.中启动的9000端口,写一个html文件向9000端口发送请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="http://localhost:9000" method="post">
<input type="text" name="username" id="">
<input type="password" name="password" id="">
<input type="submit" value="提交">
</form>
</body>
</html>
成功显示响应结果
4.获取请求体和请求头
// 1.导入http模块
const http = require('http');
// 2.创建服务对象
const server=http.createServer((request,response)=>{
response.setHeader('Content-Type','text/html;charset=utf-8');
// 获取请求的方法
console.log(request.method);
// 获取请求的路径
console.log(request.url);
// 获取请求的HTTP版本
console.log(request.httpVersion);
// 获取请求的请求头
console.log(request.headers);
// 响应体
response.end('NodeJS');
});
// 3.监听端口,启动服务
// (1.端口号,2.回调函数=》服务启动成功后的操作)
server.listen(9000,()=>{
console.log('服务启动成功');
});