1.3 定义一个get路由
-
当 url 后带参数时,运用 url.split(’?’)[0] 方法把ur和参数分隔开。
-
req.method
方法判断使用的是 post 请求还是 get 请求。
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url
const path = url.split('?')[0] // /api/list?a=10
const method = req.method
// 定义路由:模拟获取留言板列表
if (path === '/api/list' && method === 'GET') {
res.end('this is list router')
}
// 定义路由:模拟创建留言
if (path === 'api/create' && method === 'POST') {
res.end('this is create router')
}
res.end('404')
})
server.listen(3000) //可以监听http请求
console.log('http请求已经被监听,3000端口');
1.4 querystring 的使用
-
什么是querystring?
- url 问号?后面的都是 querystring (也叫 url 参数)
- & 分割,key = value 形式,可继续扩展
-
如何利用 quetystring 实现动态网页?
- 服务端拿到 querystring
- 根据不同的 querystring ,返回不同的内容
-
使用 querystring
const queryStr = url.split('?')[1] // a=100&b=200 // 解析 querystring const query = {} queryStr && queryStr.split('&').forEach(item => { // item 即 a=100 形式 const key = item.split('=')[0] // 'a' const val = item.split('=')[1] // '100' query[key] = val // { a: '100', b: '200' }
queryStr && queryStr.split(’&’).forEach 形式,是为了防止 favicon.ico 的干扰
-
使用 querystring (简易方法)
-
加入:
const querystring = require('querystring')
const query = querystring.parse(queryStr)
跟上述返回结果相同
-
1.5 res 返回数据
- 返回 json 格式:
// 定义路由:模拟获取留言板列表
if (path === '/api/list' && method === 'GET') {
// 返回结果
const result = {
errno: 0,
data: [
{ user: '张三', content: '留言1' },
{ user: '李四', content: '留言2' },
]
}
res.writeHead('200', { 'Content-type': 'application/json' })
res.end( JSON.stringify(result) ) // res.end() 中只能是字符串
}
// 定义路由:模拟创建留言
if (path === 'api/create' && method === 'POST') {
const result = {
errno: 0,
message: '创建成功'
}
res.writeHead(200, { 'Content-type': 'application/json' })
res.end( JSON.stringify(result) )
}
res.writeHead('404', { 'Content-type': 'text/plain' })
res.end('404 Not Found')
- res.end()方法中只能传入字符串,所以用 JSON.stringify() 方法把对象转换成字符串
- 200 和 404 是状态码
- res.writeHead(200, { ‘Content-type’: ‘application/json’ }) 改变状态码和文本类型
-
返回 html 格式:
res.writeHead(404, { 'Content-type': 'text/html' }) res.end(` <!DOCTYPE html> <html> <head> <title>404</title> </head> <body> <h1>404 Not Found</h1> </body> </html> `)
浏览器会根据 Content-type 识别出 html 格式