1.目的
了解nodejs
了解后端
读取本地文件
连接数据库
响应请求
2.检测是否有node
进入C盘根目录下,输入node -v ,回车出现版本号即为存在
3.初始化项目
进入C盘根目录下,新建文件md mynode
进入mynode文件,cd mynode
初始化 npm init -y
4.使用第三方模块
npm i axios -S 安装模块
const axios=require("axios")导入模块
axios.get(url).then(res=>{})使用模块
5.使用自定义模块
定义模块 utils.js
module.esports={
max(){},
randomStr(){}
}
导入与使用
导入1
const utils=require("./utils.js")
使用1
utils.max()
utils.randomStr()
导入2
const {max,randomStr}=require("./utils.js")
使用2
console.log(max(55,88),randomStr())
6.项目运行
配置命令
package.json->script
"serve":"node main.js"
npm run serve
cmd操作
进入项目目录
node main.js
7.mysql命令
查询select
查询所有
select * from `feedback` where 1;
指定列查询
select `msg`,`name` from `feedback` where 1;
添加查询条件
select * from `feedback` where name='小夏';
查询msg中包含“留”的元素,%代表任意字符
select * from `feedback` where msg like '%留%';
_代表任意一个字符串
select * from `feedback` where msg like '第_条%';
按时间排序 desc降序,默认为asc
select * from `feedback` where 1 order by `datatime` desc;
查询偏移2个 截取3行
select * from `feedback` where 1 order by `datatime` desc limit 2,3;
增加 insert into
修改 update
删除delete
8.node操作sql
安装 npm i mysql -S
导入
const mysql=require("mysql")
创建连接
const conn=mysql.creatConnection({
host:"localhost",
user:"root",
password:"",
database:"feed"
})
连接数据库
conn.connect(function(err){if(!err){console.log("数据库连接成功")}})
定义sql
var sql="select * from feedback where 1";
执行sql
conn.query(sql,function((err,result){
if(!err){
console.log(result)}
}))
断开数据库
conn.end(function(){console.log('数据库已断开')})
9.内置服务器创建
导入http
const http=require("http")
创建服务
const server=http.createServer(function(req,res){ //req请求数据res相应数据
res.statusCode=200;//响应码
res.setHeader("Content-Type","application/json")//响应类型
res.end(`{}`) //返回的数据
})
监听端口
server.listen(8888,function(){
console.log("localhost:8888 启动")
})