标签:username cal lis dbn any 请求 const ring chunk
let http = require(‘http‘);
// 引入url模块 获取域名后面的url
let path = require(‘path‘);
let fs = require(‘fs‘);
let url = require(‘url‘);
let ejs = require(‘ejs‘);
let querystring = require(‘querystring‘);
let routes = require(‘./js/routes‘);
const MongoClient = require(‘mongodb‘).MongoClient;
// Connection URL
const mongodbUrl = ‘mongodb://localhost:27017‘;
// Database Name
const dbName = ‘test‘;
// 创建http服务
// request 获取客户端传过来的信息,response 给浏览器响应的信息
http.createServer((request, response) => {
let queryUrl = url.parse(request.url).pathname === ‘/‘ ? ‘index‘ : url.parse(request.url).pathname.replace(‘/‘, ‘‘);
let pageData;
routes.static(request, response);
try {
routes.route[queryUrl](request, response, pageData);
} catch (e) {
routes.route[‘error‘](request, response, pageData);
}
// 获取get请求数据
let getData = url.parse(request.url, true);
// console.log(getData[‘query‘]);
// 路由
if(queryUrl === ‘doPost‘) {
//获取 POST 传值
let postData = ‘‘;
// 数据块接收中
request.on(‘data‘, function (postDataChunk) {
postData += postDataChunk;
});
// 数据接收完毕,执行回调函数
request.on(‘end‘, function () {
try {
postData = JSON.parse(postData);
} catch (e) {
}
request.query = querystring.parse(postData);
console.log(request.query);
// Use connect method to connect to the server
MongoClient.connect(mongodbUrl,{ useUnifiedTopology: true }, function(err, client) {
// assert.equal(null, err);
if (err) { console.log(err); return}
console.log(‘数据库连接成功‘);
const db = client.db(dbName);
const collection = db.collection(‘admin‘);
// 添加数据
collection.insertMany([
{‘name‘: request.query[‘username‘], ‘age‘: request.query[‘password‘]},
], function(err, result) {
if (err) { console.log(err); return}
// assert.equal(err, null);
// assert.equal(3, result.result.n);
// assert.equal(3, result.ops.length);
client.close();
console.log(‘添加成功‘);
});
// 删除数据
// collection.deleteOne({ ‘name‘ : ‘qqq‘ }, function(err, result) {
// if (err) { console.log(err); return}
// // assert.equal(err, null);
// // assert.equal(1, result.result.n);
// // client.close();
// console.log(‘删除成功‘);
// });
// 修改更新数据
// collection.updateOne(
// { ‘name‘ : ‘www‘ },
// { $set: { ‘name‘ : ‘111‘ } },
// (err, result) => {
// if (err) { console.log(err); return}
// // assert.equal(err, null);
// // assert.equal(1, result.result.n);
// console.log(‘更新成功‘);
// client.close();
// });
// 查看数据
collection.find({}).toArray(function(err, docs) {
if (err) { console.log(err); return}
// assert.equal(err, null);
response.end(docs);
pageData = docs;
console.log(docs);
client.close();
});
});
});
}
try {
routes.route[queryUrl](request, response, pageData);
} catch (e) {
routes.route[‘error‘](request, response, pageData);
}
}).listen(3000);
console.log(‘httpServer http://127.0.0.1:3000‘);
标签:username cal lis dbn any 请求 const ring chunk
原文地址:https://www.cnblogs.com/zhaofeis/p/14618623.html