GET/POST请求
HTTP请求?
GET(地址栏请求 直接通过URL请求)
POST(表单请求)
DELETE(删除)
PUT(更新)
1.GET请求
由于GET请求直接被嵌入在路径中,URL是完整的请求路径,包括了?后面的部分,因此可以手动解析后面的内容作为GET请求的参数
var http = require("http")
var url = require("url")
var util = require("util")
// 创建服务器
http.createServer(function(req,res){
// 输出响应头
res.writeHead(200,{"Conetent-Type":'text/plain;charset=utf-8'});
res.end(util.inspect(url.parse(req.url,true)))
}).listen(8888)
console.log(`服务器已启动。。。访问:http://127.0.0.1:8888`);
2.POST请求
POST请求的内容全部的都在请求体中,http.ServerRequest并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
比如上传文件,而很多时候我们可能并不需要理会请求体的内容,恶意的POST请求会大大消耗服务器的资源,所以node.js 默认是不会解析请求体的,当你需要的时候,需要手动来做。
const http = require('http');
const querystring = require('querystring')
//表单页面内容
var postHTML =
'<html><head><meta charset="utf-8"><title>编程师Node.js实例</title></head>'+
'<body>'+
'<form method = "post">'+
'姓名:<input name="name"><br>'+
'性别:<input name="class"><br>'+
'<input type = "submit">'+
'</form>'+
'</bory></html>';
http.createServer(function(req,res){
var body='';
req.on("data",function(turck){
body+=turck
})
req.on("end",function(){
body = querystring.parse(body)
res.writeHead(200,{"Content-Type":'text/html;charset=utf-8'})
if (body.name&&body.class) {
// 执行提交操作,获取提交信息,并输出
res.write(`姓名:${body.name}`)
res.write('<br>')
res.write(`班级:${body.class}`)
} else {
// 说明是第一次加载,需要显示表单
res.write(postHTML)
}
res.end();
})
}).listen(8888)
console.log(`服务器已启动。。。访问:http://127.0.0.1:8888`);
WEB模块
web服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序。
Web服务器的基本功能就是提供Web信息浏览服务。它只需支持HTTP协议、HTML文档格式及URL,与客户端的网络浏览器配合。大多数Web服务器都支持服务端的脚本语言(Java、C#、php、python)等,并通过脚本语言从数据库获取数据,将结果返回给客户端浏览器。
目前最主流的三个Web 服务器是Apache、Nginx、IIS。
创建服务器
const http = require("http")
const url = require("url")
const fs = require("fs")
// 创建服务器
http.createServer(function(request,response){
// 获取pathname
let pathname = url.parse(request.url).pathname;
console.log(pathname);
// 进行判断
if (!pathname||pathname=='/') {
pathname = '/index.html'
}
// 读取文件
fs.readFile(pathname.substr(1),function(err,data){
if (err) {
response.writeHead(404,{"Content-Type":"text/Html"})
} else {
response.writeHead(200,{"Content-Type":"text/Html"})
response.write(data.toString())
}
response.end()
})
}).listen(8888)
console.log(`服务器已启动。。。访问:http://127.0.0.1:8888`);
HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>啦啦啦来得及哇jio得</h1>
</body>
</html>
clien.js
const http = require("http")
// 用于请求的选型
var options={
host:'localhost',
port:'8888',
path:'/index.html'
}
// 处理响应的回调函数
function callback(res){
var body=''
res.on('data',function(trunk){
body+=trunk
})
res.on("end",function(){
console.log(body);
})
}
var req = http.request(options,callback)
req.end()