一些说明
需要用到的包
const http = require('http');
const mysql = require('mysql');
const querystring = require('querystring');
const url = require("url");
get请求从url中获取;
post请求从请求体中获取;
获取get请求的参数
example:请求地址
http://localhost:9000/getalluser?name=lin&v_id=3&time=2020-10-09
let initurl = request.url;
console.log(initurl)
///getalluser?name=lin&v_id=3&time=2020-10-09
let urlObj = url.parse(initurl);
console.log(urlObj)
打印的内容如下:
url对象
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?name=lin&v_id=3&time=2020-10-09',
query: 'name=lin&v_id=3&time=2020-10-09',
pathname: '/getalluser',
path: '/getalluser?name=lin&v_id=3&time=2020-10-09',
href: '/getalluser?name=lin&v_id=3&time=2020-10-09'
}
//将请求的参数转化为对象
let queryObj = querystring.parse(urlObj.query)
console.log(queryObj )
获取post请求的参数
example
请求的地址:http://localhost:9000/getnoteevent
server.on('request', (request, response) => {
let body="";
// 获取post请求的参数
if(request.method == 'POST'){
request.on('data', (chunk) => {
body += chunk;
});
}
}
代码
// 创建一个web服务器
const server = http.createServer((req, res) => {
res.statusCode = 200;
// res.setHeader('Content-Type', "text/html;charset=utf-8");
res.setHeader('Content-Type','text/plain');
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
})
server.on('request', (request, response) => {
// 请求的路径:/getalluser?name=lin&v_id=3&time=2020-10-09
let initurl = request.url;
let body="";
// 获取post请求的参数
if(request.method == 'POST'){
request.on('data', (chunk) => {
body += chunk;
});
}
let urlObj = url.parse(initurl);
let queryObj = querystring.parse(urlObj.query)
console.log('priiii',queryObj);
if(urlObj.pathname == '/favicon.ico' || urlObj.pathname == ''){
return;
}
if (urlObj.pathname === '/getnoteevent') {
console.log('post请求参数',JSON.parse(chunk));
// 查询数据
connection.query('select * from t_note_event', (err, row) => {
if (err) {
console.log(err);
}else{
let data = JSON.stringify(row);
response.end(data);
}
})
}
if(urlObj.pathname == '/getalluser'){
console.log('get请求体参数',queryObj);
connection.query('select * from t_note_user', (err, row) => {
if (err) {
console.log(err);
}else{
let data = JSON.stringify(row);
response.end(data);
}
})
}
})
// 监听9000端口
server.listen(9000, () => {
console.log('服务器启动了。。。')
})