服务器端基本概念
在使用浏览器对网站进行访问可以使用 http://baidu.com 进行访问,Node.js 可以搭建一个本地的服务器,Node.js 所搭建的本地服务器所使用的通信协议使用的 localhost 协议,例如使用 Node.js 监听 3000 端口,那么在浏览器中可以输入 localhost:3000 来访问这个服务器。
使用 Node.js 创建 web 服务器
需要使用内置模块 http,如下代码所示:
const http = require('http')
// 调用 createServer 方法创建一个服务器对象,将创建之后的对象保存到变量中
let app = http.createServer()
// 监听该服务器的 request 事件
// 回调函数中 req 代表请求信息,res 代表响应信息
app.on('request', (req,res)=>{
// 向html 中写入内容
res.write(`<h1>hello world</h1>`)
// 调用 end 方法结束响应,如果没有end 方法,则页面会造成假死现象
res.end()
})
// 监听3000端口
app.listen(3000)
上述代码第 4 行创建了服务器对象,将对象保存到 app 变量中;
由于 Node.js 是基与事件驱动的,所以第 8 行代码使用 on()
方法监听 request
事件,所有有关客户端的事放到了回调函数中的第一个参数 req
中,所有有关服务端的事放到了回调函数中的第二个参数 res
中。
需要注意的是,14 行代码调用了 end
方法,必须调用一次 end
方法,否则访问页面时页面会一直呈刷新状态。
最后监听了 3000 端口。
在终端中输入 nodemon 02_sever.js
运行,然后在浏览器中输入 localhost:3000 可以访问生成的页面。
页面中安静的躺着十个大字 “hello world”。
http
获取请求方式
需要使用请求对象的 method
属性,可以获得客户端向服务端发送的请求。如下代码所示:
const http = require('http')
let app = http.createServer()
app.on('request', (req,res) =>{
res.write(`<h1>hello</h1>`)
console.log(req.method)
res.end()
})
app.listen(3000)
在浏览器地址栏中输入 localhost:3000
,终端中输入结果如下:
GET
GET
接下来模拟 ajax 向服务端提交数据:
客户端页面:
<body>
<form action="http://localhost:3000/" method="post">
<input type="text">
<input type="submit">
</form>
</body>
Node.js 服务端:
const http = require('http')
let app = http.createServer()
app.on('request', (req,res) =>{
res.write(`<h1>hello</h1>`)
console.log(req.method)
res.end()
})
app.listen(3000)
结果:
有了请求方式后,nodejs 可以根据请求方式从而做出不同的响应,如下代码所示:
const http = require('http')
let app = http.createServer()
app.on('request', (req,res) =>{
res.write(`<h1>hello</h1>`)
if (req.method === 'POST'){
res.write('post')
// code...
}else if (req.method === 'GET'){
res.write('get ')
// code...
}
res.end()
})
app.listen(