Node.js搭建WEB服务器

1. 安装Node和nodemon插件

#全局安装nodemon插件
npm i nodemon -g

2. 引入http模块

cosnt http = require('http')

3. 创建服务监听端口

const server = http.createServer((req,res) => {
    if(req.method==='GET'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('get请求');
    }else if(req.method==='POST'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('post请求');
    }else{
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('其他请求');
    }
})

server.listen(3000,()=>{
    console.log('服务器启动成功')
})

4. 解析接口地址

#引入url
const url = require('url')

const server = http.createServer((req,res) => {
	
	cosnt {pathname} = url.parse(res.url)
    if(req.method==='GET' && pathname === '/getInfo'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('get请求');
    }else if(req.method==='POST'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('post请求');
    }else{
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('其他请求');
    }
})

5. 解析get参数

使用url解构出query参数,再使用querystring格式化参数

const qs = require('querystring')

const server = http.createServer((req,res) => {
	
	cosnt {pathname,query} = url.parse(res.url)
    if(req.method==='GET' && pathname === '/getInfo'){
        console.log(qs.parse(query))
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('get请求');
    }else if(req.method==='POST'){
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('post请求');
    }else{
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('其他请求');
    }
})

6. 解析post参数

const server = http.createServer((req,res) => {
	
	cosnt {pathname,query} = url.parse(res.url)
    if(req.method==='GET' && pathname === '/getInfo'){
        console.log(qs.parse(query))
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('get请求');
    }else if(req.method==='POST'){
    	//接受参数
    	let data = ''
    	req.on('data',temp => {
    	data += temp
    	})
		//接受参数完毕解析
		req.on('end',()=>{
		console.log(qs.data)
		res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('post请求');
		})
        
    }else{
        res.setHeader('Content-Type','text/plain;charset=utf-8')
        res.end('其他请求');
    }
})