Node.js是一种基于Chrome V8引擎的JavaScript运行时环境,可以让JavaScript在服务器端运行,是一种非常流行的开发工具。在本篇博客文章中,我将介绍Node.js的一些基本概念和用法
node作用
-当js代码引入到html中,在浏览器中运行的时候,叫做前端js,用来操作DOM和BOW,完成网页特效
-当js代码通过node软件运行的时候,没有DOM和BOM的操作,而是读取电脑硬盘 读写文件 操作数据库等;-可以当作电脑系统和数据库的时候,就可以当作服务器来使用
NodeJS安装
下载地址
测试
win+r键输入cmd进入命令行
node –v 查看版本
看到版本号就是安装成功
node项目
-01初始化项目
npm init -y
-02 安装mysql包(插件)
npm i mysql
-03 创建index.js文件
模块导入导出
01导出
module.exports = conn;
02导入
const conn = require("./conn.js")
在nodejs中连接数据
01 导入mysql
const mysql = require("mysql")
02 创建连接
const conn = mysql.createConnection({host,user,password,database})
03 连接
conn.connect(function(err){ if(err){ console.err("数据库连接失败",err) } })
04 定义sql
const sql = "select * from comment where 1"
05 执行sql
conn.query(sql,function(err,data){ //data是数据库返回的数据 })
06 关闭sql
conn.end(function(err){})
http开启服务器
01 导入http
const http = require("http")
02 创建服务器
const http = require("http")
03 监听端口
server.listen(8080,()=>{console.log("服务器开启成功 http://localhost:8080")})
express 更好用的nodejs 服务器框架
01 安装框架
npm i express
02 创建app
const express = require("express") const app = express()
03 监听路由
app.get("/",function(req,res){ res.send("<h1>首页内容</h1>") }) app.post("/",function(req,res){ res.send("<h1>post首页内容</h1>") }) app.get("/about",function(req,res){ res.send("<h1>关于首页</h1>") })
04 监听端口
app.listen(8888,function(){ console.log("服务器开启成功 http://localhost:8888") })
express 使用静态文件夹
通常是public 在public内容可以在浏览器里面自动访问
public要和当前文件夹放在同一目录
浏览器访问public目录相对于/
app.use(express.static("public"))
总之,Node.js是一个非常有用的工具,可以让JavaScript在服务器端运行。它可以用来创建服务器、处理文件系统和处理异步编程。如果你想学习更多关于Node.js的知识,可以查看官方文档和社区资源。
const conn = require("./conn.js") //导入数据库连接
// 01 导入原生http服务
const http = require("http")
// 02 创建服务器
const server = http.createServer((req,res)=>{
// req,request浏览器的请求数据
// res,response 服务器返回给浏览器的数据
// 01 状态码status,02 数据类型content-type
// 03 响应体
res.statusCode = 200;//200代表成功
res.setHeader("Content-Type","application/json;charset=utf-8")
// res.end('{"errCode":0,"msg":"欢迎你的到来","data":"数据库返回的数据"}')
const sql = "select * from comment where 1"; //sql
conn.query(sql,(err,data)=>{ // 执行sql
if(err){
var result = {"errCode":1,"msg":"数据库错误","err":err} //错误数据返回
}else{
var result = {"errCode":0,"msg":"获取成功","data":data} //正确数据返回
}
res.end(JSON.stringify(result))
})
})
// 03 监听端口
server.listen(8080,()=>{
console.log("服务器启动成功");
console.log("访问: http://localhost:8080")
})
//导入mysql
const mysql = require('mysql');
//创建连接
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '158976',
database: 'feedback',
})
//连接
conn.connect(err=> {
if (err) {
console.log('连接错误!', err)
}
});
//导出连接
module.exports = conn;