nodejs
nodejs可以干嘛:
- 独立编写和运行js代码
- 文件操作
- 架设服务器
- npm下载依赖
- 操作数据库(db)
Mongodb(非关系型数据库)
MySQL关系型数据库
node指令作用,通过win+r输入cmd控制台中
- DOS平台指令(disk operating system磁盘操作系统)
输入node -v查看node版本号
ctrl+c终止指令
cls清屏
ipconfig查看ip地址
node 需要执行的js文件
dir查看当前盘信息
D:进入D盘,不同的盘要先切换盘才能cd
cd 文件路径,进入当前盘的文件路径
cd …返回上一级文件夹
cd /返回根目录 - 直接node进入node平台,node平台指令
.help查看帮助
.exit退出node平台
文件操作
let fs = require("fs");
fs.readFile("1.txt",function(err,result){
console.log(result.toString())
})
fs.writeFile("2.txt","写入的信息",function(err){})
fs.appendFile("2.txt","追加的信息",function(err){})
- 通过require方法引入node的文件系统模块fs
- fs.readFile(path,options,callback)读取文件方法
path:表示要读取的文件路径
options:表示以什么编码格式来读取文件,默认utf-8,可以省略不写
callback:文件读取完成后的回调函数,里面两个参数,err读取失败,result读取成功的信息 - fs.writeFile(path,data,callback)写入文件方法
path需要写入的文件路径,
当写入的文件没有时,会创建一个新文件写入进去,不能创建路径,只能创建文件
写入的信息会覆盖文件的原信息
data需要写入的信息
callback写入成功后的回调函数,参数err,写入失败的结果 - fs.appendFile(path,data,function(err){})在文件内容后面加入数据
- fs.mkdir(“文件夹名”,function(err){})创建文件夹,同步写法,fs.mkdirSync(“文件夹名”)
- fs.exists(“文件夹名”,function(err){})判断文件夹是否存在,同步写法:fs.existsSync(“文件夹名”)
- fs.rmdir(“文件夹名”,function(err){})删除文件夹,同步写法:fs.rmdirSync(“文件夹名”);
创建服务器
//写法一
let http = require("http")//引入http工具
function doRequest(request,response){
console.log("服务器接收到请求")
response.end("<h1 style="color:red;">你好</h1>")
}
let server = http.createServer(doRequest);
server.listen(8081,function(){
console.log("启动服务器")
})
//写法二
const http = require("http");//引入http工具
const server = http.createServer();//创建服务器实例
server.on("request",(req,res)=>{//req:请求的信息,res:服务器返回信息
console.log("服务器收到请求")
res.setHeader("Content-type","text/html;charset=utf-8")//设置返回的头部信息,设置响应数据的类型特征
res.end("<h1 style="color:red;">你好</h1>")//发送响应数据
})
server.listen(8081,()=>{
console.log("启动服务器");//服务器启动打印信息
})
//写法三
const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});
res.end('<h1 style="color:red;">你好</h1>');
}).listen(8081,()=>{console.log('Server running at http://127.0.0.1:8888/');});
- req.url请求的地址,这里会有两次,一次是页面地址,一次是图标地址/favicon.ico,如果没有title的图标可以取消掉这个执行步骤优化速度:if(req.url==“/favicon.ico”){reurn;}
获取表单get提交的数据
- 在html文件中
<form action="http://127.0.0.1:8081" method="get">
<input type="text" name="name">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
- 在js文件中
const http = require('http');
const url = require("url");//引入url工具
http.createServer(function (req, res) {
if(req.url=="/favicon.ico"){
return;
}
let str = req.url;//文件地址的url字符串,get提交的数据会存在url中
let obj = JSON.parse(JSON.stringify(url.parse(str,true)));//把这个字符串信息转换成对象,true的作用是把对象里面的query属性值转成对象
res.writeHead(200, {'Content-Type': 'text/html;charset=utf-8'});//发送http头部信息,编码格式
res.end(`姓名:${obj.query.name}<br/>年龄:${obj.query.age}`);//发送响应数据
}).listen(8081,()=>{console.log('启动服务器');});
url.parse(req.url,true)把req.url请求的地址转成对象,里面的true是把这个对象里面的query属性值转成对象
url.parse(req.url,true).query.表单里面输入框的name属性值,就能获取到表单get方式提交的数据,
直接打印url.parse(req.url,true).query前面有一堆没用字符,所以用JSON.parse(JSON.stringify())把他转成正常的对象
获取表单post提交的数据
在html文件中
<form action="http://127.0.0.1:8081" method="post">
<input type="text" name="name">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
在js文件中
let http = require("http");
let querystring = require("querystring");//引入querystring工具
let util = require("util");//引入util工具
http.createServer((req,res)=>{
if(req.url=="/favicon.ico"){
return;
}
let post="";//定义一个空字符串用来接收每次传过来的数据
req.on("data",(chunk)=>{//接监听data事件,每次接收到请求体的数据都把他加到空字符串中去
post+=chunk
})
req.on("end",()=>{//监听end事件,接收完的事件
post = JSON.parse(JSON.stringify(querystring.parse(post)));//querystring.parse方法把存储数据的字符串转成对象
console.log(post);
res.end(util.inspect(post));
})
res.writeHead(200,{'Content-Type':'text/html;charset=utf8'})//设置响应头部信息和编码规则
}).listen(8081,()=>{
console.log("启动成功");
})
获取ajax提交的数据
- a标签,表单,地址的请求都会刷新页面,ajax不会刷新页面
跨域
- 同源:请求方和被请求方的协议名ip地址和端口号都相同
- 不同源的请求就称之为跨域
- ajax的跨域请求会被浏览器默认禁止接收响应数据
- 解决方法
1.cors:在服务器端加上res.writeHead(200,{‘Content-Type’:‘text/html;charset=utf8’,“Access-Control-Allow-Origin”:“*”});
2.JSONP:利用js标签发送请求
3.代理服务器:Proxy Ngnix,利用代理服务器给服务器发请求跳过浏览器 - post请求在ajax中要设置请求体
xhr.setRequestHeader(“Content-Type”,“application/x-www-form-urlencoded”)用于传键值对的参数
xhr.setRequestHeader(“Content-Type”,“application/json;charset=utf-8”)用于传json字符串参数
xhr.setRequestHeader(“Content-Type”,“multipart/form-data”)用于文件上传 - ajax的post请求示例代码
html文件
姓名:<input type="text" name="sname" id="sname"><br/>
年龄:<input type="text" name="age" id="age"><br/>
工作:<input type="text" name="job" id="job">
<input type="button" value="提交" id="btn-ajax"><br/>
<div></div>
<script>
let btn_ajax = document.querySelector("#btn-ajax");
let sname = document.querySelector("#sname");
let d = document.querySelector("div");
btn_ajax.addEventListener("click",function(){
let xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:8081?a=5&b=6");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send(`sname=${sname.value}&age=${age.value}&job=${job.value}`);
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status>=200 && xhr.status<300){
d.innerHTML = xhr.responseText;
}
}
})
</script>
js文件
let http = require("http");
let querystring = require("querystring");
let url = require("url");
http.createServer((req,res)=>{
if(req.url=="/favicon.ico"){
res.end("");
return;
}
let obj;
res.writeHead(200,{'Content-Type':'text/html;charset=utf8',"Access-Control-Allow-Origin":"*"});
if(req.method=="GET"){
obj = JSON.parse(JSON.stringify(url.parse(req.url,true).query))
res.end(`<p>姓名:${obj.sname}</p><p>年龄:${obj.age}</p><p>工作:${obj.job}</p>`)
}else if(req.method=="POST"){
let post = "";
req.on("data",(chunk)=>{
post+=chunk;
})
req.on("end",()=>{
obj = JSON.parse(JSON.stringify(querystring.parse(post)))
console.log(obj);
res.end(`<p>姓名:${obj.sname}</p><p>年龄:${obj.age}</p><p>工作:${obj.job}</p>`)
})
}
}).listen(8081,()=>{console.log("启动成功");})