代码如下:
let http = require('http');
// 对url路径进行处理
let url = require('url');
let obj = [20, 20, 20, 20, 20, 20]
http.createServer((req, res) => {
if (req.url === '/favicon.ico') return false;
res.writeHead(200, {
// text/html html字符串格式
// text/plain 普通文本字符串
'content-type': 'text/plain;charset=utf-8',
// 允许跨域
'Access-Control-Allow-Origin': '*'
});
// post请求
if (req.method.toLowerCase() === 'post' && req.url === '/temp/PostAllParameter') {
if (req.url === '/temp/PostAllParameter') {
let alldata_ = '';
req.on('data', function (chunk) {
alldata_ += chunk;
})
req.on('end', function () {
// 将传递过来拼接的字符串转化成一个数组
alldata_ = new URLSearchParams(alldata_);
console.log(alldata_);
res.end(JSON.stringify(alldata_));
})
}
}
// get请求
else {
// let url_o = url.parse(req.url,true);
let url_o = new URL(req.url, 'http://127.0.0.1:12601')
if (url_o.pathname === '/add/') {
res.write(url_o.searchParams.get('name') + url_o.searchParams.get('age'))
} else if (url_o.pathname === '/temp/findAllParameter/') {
res.write(JSON.stringify(obj))
} else {
res.end();
}
// url_o.query为传递的参数
// console.log(url_o.searchParams.get('name'))
res.end();
}
}).listen(12601, '127.0.0.1', () => console.log('http://127.0.0.1:12601'))