Node开发服务器:
Node.js:并不是一门新的语言 ,只是javascript另外一个运行环境
将js从前端带到服务器
ajax:把前端的内容发送给服务器·,提交一个ajax请求
一个服务器里会有很多的端口,不同的服务器可能有相同的端口名字,但是服务器不能相同;
Node开发服务器:
1.启动服务器,编写api接口
- http模块:用于启动服务器
- .createServer(function(){})创建服务
- req:requset 前端发送过来的参数
- res:response 返回给前端的内容
//启动服务器
// http模块:用于启动服务器
const http = require("http")//引入http模块
const server = http.createServer((req, res) => {
//利用res参数 给前端返回内容
console.log("hello world")
res.write("hello world")
//.end()发送内容
res.end()
})
//设置端口号 当前服务的端口为8088
server.listen(8088)
node启动
- 在根目录右键git bath here
- 输入 node (js文件名)按下tab键。如果有多项,可以输入node 1+tab键
- 在浏览器首页输入:localhost:8088。就可以返回文件内容。浏览器的地址栏:就是一个ajax请求 get请求
- ctrl+c 终止服务器
2.跟数据库进行交互 增删改查
3.操作静态文件
1、如何利用fs写入内容
//fs.writeFile(路径,写入内容,回调函数)
//回调函数 err参数, 如果写入错误 err保存错误信息,如果没有错误 err就是空值
fs.writeFile("./a.txt", "hello world", err => {
if (err) {
console.log("写入失败")
} else {
console.log('写入成功')
}
})
2、如何读取指定文件
新建一个a.html文件,在a.html输入hello word。
- fs.readFile(路径,回调函数)
- err :如果读取错误 err保存错误信息,没有错误空
- data:读取到内容
//操作静态文件 fs模块
const fs = require("fs")
fs.readFile("./a.txt", (err, data) => {
if (err) {
console.log("读取失败")
} else {
//Buffer数据类型 二进制码
//计算机之间进行文件传输时使用的内容
console.log(data.toString())//<Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>二进制字符加string转为字符串
}
})
3、如何在服务器端打开网页
根据地址打开指定的页面
localhost:8088/a.html
http://localhost:8088/a.html
const http = require("http")// http模块:用于启动服务器
const fs=require("fs")//操作静态文件 fs模块
const server = http.createServer((req, res) => {//.createServer(function(){})创建服务
let url=req.url //请求的地址
if (url == "/a.html") {//打开a页面
//读取指定的静态文件
fs.readFile("./a.html", (err, data) => {
if (err) {
res.write("没有找到对应页")
res.end()
} else {
res.write(data)
res.end()
}
})
}
})
server.listen(8088)