绪论
用NodeJs没做过大项目,都是自己用来玩耍,记录一下。
问题:
- 怎样写一个最简单的服务器,输出内容到网页上。
- 用Vue.js写的前端项目,怎样用NodeJs在本地运行。
- 写小项目接口,不想连接MySQL数据库等,但是会有少量数据,还要能做到增删改查,怎么办?
- 写小项目接口,连接MySQL数据库怎么做。
正文
问题一
代码
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type" : "text/plain;charset=utf-8" // 输出类型
});
response.write("你好");// 页面输出
response.end();
}).listen(10000); // 监听端口号
console.log("服务器启动!");
启动服务
结果
问题二
使用vscode打包vue.js项目会生成dist文件夹,里面会有首页及相关的静态文件。
代码
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
next();
});
app.use(express.static(path.resolve(__dirname, 'E:\\Tools\\nodejs\\dist')));
app.get('/index', function (req, res) {
const html = fs.readFileSync(path.resolve(__dirname, 'E:\\Tools\\nodejs\\dist\\index.html'), 'utf-8')
res.send(html)
})
app.listen(10001, function () {
console.log('服务器启动: http://localhost:10001');
});
问题三
代码
const fs = require('fs');
const express = require('express');
const app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
next();
});
// 获取数据
function queryMyData() {
return JSON.parse(fs.readFileSync('./myData.json'));
}
// 写入数据
function writeMyFile(str) {
var flag = !0;
fs.writeFile('./myData.json', str, function(err) {
if (err) {
flag = !1;
console.error('----写入失败----');
} else {
console.log('----写入成功----');
}
});
return flag;
}
// 查询
app.get('/api/queryData', function(req, res) {
console.log('访问: /api/queryData');
res.header("Content-Type", "application/json;charset=utf-8");
var id = req.query.id || '';
// 获取数据
var json = queryMyData();
var nJson = {user:[], total:0};
if (id != '') {
for (var i = 0; i < json.user.length; i++) {
var u = json.user[i];
if (u.id == id) {
nJson.user.push(u);
}
}
} else {
nJson = json;
}
nJson.total = nJson.user.length;
res.end(JSON.stringify(nJson));
});
// 新增
app.get('/api/addData', function(req, res) {
console.log('访问: /api/addData');
res.header("Content-Type", "application/json;charset=utf-8");
var _id = req.query.id || '';
var _name = req.query.name || '';
// 返回内容
var response = {};
if (_id == '' || _name == '') {
response.message = '不能为空';
} else {
// 获取数据
var json = queryMyData();
// 判断id是否存在
var a = !0;
for (var i = 0; a && i < json.user.length; i++) {
if (json.user[i].id == _id) {
a = !1;
break;
}
}
if (!a) {
response.message = '该ID存在';
} else {
json.user.push({id: _id, name: _name});
json.total = json.user.length;
var b = writeMyFile(JSON.stringify(json));
if (b) {
response.message = '新增成功';
} else {
response.message = '新增失败';
}
}
}
res.end(JSON.stringify(response));
});
// 修改
app.get('/api/editData', function(req, res) {
console.log('访问: /api/editData');
res.header("Content-Type", "application/json;charset=utf-8");
var _id = req.query.id || '';
var _name = req.query.name || '';
// 返回内容
var response = {};
if (_id == '' || _name == '') {
response.message = '不能为空';
} else {
// 获取数据
var json = queryMyData();
// 判断id是否存在
var a = !0;
for (var i = 0; a && i < json.user.length; i++) {
var u = json.user[i];
if (u.id == _id) {
u.name = _name;
a = !1;
break;
}
}
if (a) {
response.message = '该ID不存在';
} else {
var b = writeMyFile(JSON.stringify(json));
if (b) {
response.message = '修改成功';
} else {
response.message = '修改失败';
}
}
}
res.end(JSON.stringify(response));
});
// 删除
app.get('/api/delData', function(req, res) {
console.log('访问: /api/delData');
res.header("Content-Type", "application/json;charset=utf-8");
var _id = req.query.id || '';
// 返回内容
var response = {};
if (_id == '') {
response.message = 'ID不能为空';
} else {
// 获取数据
var json = queryMyData();
for (var i = 0;i < json.user.length; i++) {
if (json.user[i].id == _id) {
json.user.splice(i, 1);
break;
}
}
json.total = json.user.length;
var b = writeMyFile(JSON.stringify(json));
if (b) {
response.message = '删除成功';
} else {
response.message = '删除失败';
}
}
res.end(JSON.stringify(response));
});
app.listen(10002, function() {
console.log('服务器启动: http://localhost:10002');
});
myData.json
{“user”:[],“total”:1}
新增
http://localhost:10002/api/addData?id=1&name=%E5%BC%A0%E4%B8%89
查询
修改
http://localhost:10002/api/editData?id=1&name=%E7%8E%8B%E4%BA%94
删除
http://localhost:10002/api/delData?id=1
问题四
代码
const express = require('express');
const app = express();
const mysql = require('mysql');
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
next();
});
var connection = mysql.createConnection({
host : '127.0.0.1',
port : '3306',
user : 'root',
password : '123456',
database : 'my_time'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(error, results, fields) {
if (error)
throw error;
console.log('数据库连接成功');
});
// 时间
function formatDate() {
var date = new Date();
var year = date.getFullYear(), month = date.getMonth() + 1, // 月份是从0开始的
day = date.getDate(), hour = date.getHours(), min = date.getMinutes(), sec = date
.getSeconds();
var newTime = year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':'
+ sec;
return newTime;
}
//查询统计
app.get('/api/queryStatistics', function(req, res) {
res.header("Content-Type", "application/json;charset=utf-8");
// 查询语句
var sql = "SELECT COUNT(id) AS 'totalDays', SUM(if_work = '1') AS 'workDays', SUM(work_time) AS 'workTime', SUM(study_time) AS 'studyTime' FROM my_time";
connection.query(sql, function(error, results, fields) {
if (error) {
console.log('查询出错');
res.end(JSON.stringify({}));
}
console.log('\n-------------------------- SELECT ----------------------------');
console.log(formatDate() + ":" + results);
res.end(JSON.stringify(results));
});
});
//查询详情
app.get('/api/queryDetail', function(req, res) {
res.header("Content-Type", "application/json;charset=utf-8");
// 获取参数
var id = req.query.id || '';
var params = [id];
// 查询语句
var sql = " SELECT * FROM my_time where id = ? ";
connection.query(sql, params, function(error, results, fields) {
if (error) {
console.log('查询出错');
res.end(JSON.stringify({}));
}
console.log('\n-------------------------- SELECT ----------------------------');
console.log(formatDate() + ":" + results);
res.end(JSON.stringify(results));
});
});
app.listen(10001, function() {
console.log('服务器启动: http://localhost:10001');
});
结果
(若有什么错误,请留言指正,3Q)