npm init --yes
==============================================================
PS E:\vscode-workspace\AJAX> npm init --yes //初始化
Wrote to E:\vscode-workspace\AJAX\package.json:
{
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
cnpm install express --save
====================================================================
PS E:\vscode-workspace\AJAX> cnpm install express --save
√ Installed 1 packages
√ Linked 49 latest versions
√ Run 0 scripts√ All packages installed (52 packages installed from npm registry, used 1s(network 1s), speed 458.2KB/s, json 49(122.92KB), tarball 546.96KB)
写个demo初体验
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request对请求报文的封装 response对响应报文的封装
app.get('/', (request, response) => {
//设置响应
response.send('hello express');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中')
});
执行
Windows PowerShell
版权所有(C) Microsoft Corporation。保留所有权利。
安装最新的 PowerShell,了解新功能和改进!https://aka.ms/PSWindows
PS E:\vscode-workspace\AJAX\express基本使用> node .\learnexpress.js
服务已启动,8000端口监听中
写个案例,通过ajax的GET请求得到服务端(Express)响应并输出到页面中
文件名 GET.html
<!-- 前端 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX GET 请求</title>
<style>
#result {
margin-top: 50px;
width: 400px;
height: 400px;
border: 1px solid royalblue;
/* background-color: pink; */
}
</style>
</head>
<body>
<button>点击发送请求</button>
<div id="result"></div>
<script>
// ('button')[0] :第一个button
const btn = document.getElementsByTagName('button')[0];
//得到div
const resultdiv = document.getElementById('result');
btn.onclick = function() {
// 开始ajax
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化
xhr.open('GET', 'http://localhost:8000/server');
//3.发送
xhr.send();
//***绑定 处理服务端返回的结果
/*onreadystatechange
on when 当... 时候
readystate 是xhr对象中的属性,表示状态 0 1 2 3 4
0:表示未初始化
1:open方法已经调用完毕
2:send方法已经调用完毕
3:服务端返回部分结果
4:服务端返回所有结果
change 改变
*/
xhr.onreadystatechange = function() {
//判断 readyState == 4 服务端返回了所有结果
if (xhr.readyState == 4) {
//判断响应状态码 200 404 403 401 500
//2xx 响应成功
if (xhr.status >= 200 && xhr.status < 300) {
// //处理结果 行 头 空行 体
//console端打印后端返回的结果
// console.log(xhr.status); //状态码
// console.log(xhr.statusText); //状态字符串
// console.log(xhr.getAllResponseHeaders()); //所有响应头
// console.log(xhr.response); //响应体
//将反应结果插入页面的div中
resultdiv.innerHTML = xhr.response;
} else {
alert('请求失败');
}
}
}
};
</script>
</body>
</html>
//文件名 server.js
// 服务端
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request对请求报文的封装 response对响应报文的封装
app.get('/server', (request, response) => {
//设置访问路径localhost:8000/server
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('hello ajax');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中');
});
PS E:\vscode-workspace\AJAX\nativeajax> node .\server.js
服务已启动,8000端口监听中
写个案例,通过ajax的POST请求得到服务端(Express)响应数据,悬浮到div得到数据
文件名 post.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX POST 请求</title>
<style>
#result {
width: 200px;
height: 200px;
background-color: plum;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取元素
const divresult = document.getElementById('result');
//绑定事件
divresult.addEventListener("mouseover", function() {
// console.log("test");
//创建ajax对象
const xhr = new XMLHttpRequest();
//初始化,设置类型和url
xhr.open("POST", "http://localhost:8000/server");
//发送
xhr.send();
// xhr.send('name=vis.yang&age=3'); post请求参数放在send get请求在open的url后面?name=vis.yang&age=3
//事件绑定
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//处理服务端的响应体
divresult.innerHTML = xhr.response;
}
}
}
});
</script>
</body>
</html>
文件名 server.js
// 服务端
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request对请求报文的封装 response对响应报文的封装
app.post('/server', (request, response) => {
//设置访问路径localhost:8000/server
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//设置响应体
response.send('hello ajax post');
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中');
});
PS E:\vscode-workspace\AJAX\nativeajax> node .\server.js
服务已启动,8000端口监听中
设置请求头
//发送前设置响应头
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); //固定的
xhr.send();
AJAX处理json数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX处理json数据</title>
<style>
#result {
width: 200px;
height: 200px;
background-color: plum;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取元素
const divresult = document.getElementById('result');
//绑定键盘按键事件
window.onkeydown = function() {
//new 一个ajax对象
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = 'json';
xhr.open('GET', 'http://localhost:8000/server');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//解析返回的json字符串 手动转换
// let data = JSON.parse(xhr.response);
// divresult.innerHTML = data.name + ' is ' + data.age + '岁了';
//自动转换 更方便
divresult.innerHTML = xhr.response.name + ' is ' + xhr.response.age + '岁了';
}
}
};
}
</script>
</body>
</html>
// 服务端
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request对请求报文的封装 response对响应报文的封装
//app.all 处理所有格式的请求
app.all('/server', (request, response) => {
//设置访问路径localhost:8000/server
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应一个数据
const data = {
name: 'Vis.Yang',
age: '3'
};
let str = JSON.stringify(data);
//响应发送数据
response.send(str);
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中');
});
PS E:\vscode-workspace\AJAX\nativeajax> node .\server.js
服务已启动,8000端口监听中
安装nodemon 自动重启服务工具
cnpm install -g nodemon 安装nodemon
查看版本
E:\vscode-workspace\AJAX\nativeajax> nodemon -v
2.0.12 版本
E:\vscode-workspace\AJAX\nativeajax> nodemon .\server.js 启动服务
结果:
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\server.js`
服务已启动,8000端口监听中
改动服务端,自动就重启了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX处理json数据</title>
<style>
#result {
width: 200px;
height: 200px;
background-color: plum;
}
</style>
</head>
<body>
<div id="result"></div>
<script>
//获取元素
const divresult = document.getElementById('result');
//绑定键盘按键事件
window.onkeydown = function() {
//new 一个ajax对象
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = 'json';
xhr.open('GET', 'http://localhost:8000/server');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//解析返回的json字符串 手动转换
// let data = JSON.parse(xhr.response);
// divresult.innerHTML = data.name + ' is ' + data.age + '岁了';
//自动转换 更方便
divresult.innerHTML = xhr.response.name + ' is ' + xhr.response.age + '岁了' + '爱好:' + xhr.response.hobby;
}
}
};
}
</script>
</body>
</html>
// 服务端
//1.引入express
const { request, response } = require('express');
const express = require('express');
//2.创建应用对象
const app = express();
//3.创建路由规则 request对请求报文的封装 response对响应报文的封装
app.all('/server', (request, response) => {
//设置访问路径localhost:8000/server
//设置响应头 设置允许跨域
response.setHeader('Access-Control-Allow-Origin', '*');
//响应一个数据
const data = {
name: 'Vis.Yang',
age: '3',
hobby: '唱跳 rap 和 篮球',
};
let str = JSON.stringify(data);
//响应发送数据
response.send(str);
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log('服务已启动,8000端口监听中');
});
E:\vscode-workspace\AJAX\nativeajax> nodemon .\server.js
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node .\server.js`
服务已启动,8000端口监听中
[nodemon] restarting due to changes...
[nodemon] starting `node .\server.js`
服务已启动,8000端口监听中
解决IE缓存 加时间戳
xhr.open('GET', 'http://localhost:8000/server?time='+Date.now);