一、下载安装

官网地址:https://www.expressjs.com.cn/
安装
指定目录下
npm init —yes
npm i express

二、Express的使用

  1. // 1.引入express
  2. const express = require('express')
  3. // 2.创建应用对象
  4. const app = express()
  5. // 3.创建路由规则
  6. app.get('/', (request,response) =>{
  7. // 设置响应
  8. response.send('hello')
  9. });
  10. // 4.监听端口,启动服务
  11. app.listen(8000,()=>{
  12. console.log("服务已启动");
  13. });

代码编辑好之后,需要启动服务,命令为node 文件名,在浏览器输入localhost:8000即可.
测试案例:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>TestAjax</title>
  6. <style>
  7. #result{
  8. width: 200px;
  9. height: 100px;
  10. border: solid 1px #2a5caa;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <button>发送请求</button>
  16. <div id="result"></div>
  17. <script>
  18. const btn = document.getElementsByTagName('button')[0];
  19. const result = document.getElementById('result');
  20. btn.onclick = function (){
  21. // 1.创建对象
  22. const xhr = new XMLHttpRequest();
  23. // 2.初始化,设置请求方法和URL
  24. xhr.open('GET','http://localhost:8000/server')
  25. // 3.发送
  26. xhr.send();
  27. // 4.事件绑定 处理服务端返回的结果
  28. xhr.onreadystatechange = function (){
  29. // 判断状态
  30. if (xhr.readyState === 4){
  31. // 判断状态码
  32. if (xhr.status === 200 && xhr.status < 300){
  33. // 处理结果
  34. result.innerHTML = xhr.response;
  35. }else{
  36. }
  37. }
  38. }
  39. }
  40. </script>
  41. </body>
  42. </html>

效果展示:
image.png
实现在地址栏传输参数
xhr.open(‘GET’,’http://localhost:8000/server?a=200&b=300‘)

三、nodemon自动重启工具

安装:npm install -g nodemon
启动:nodemon 文件名
若启动时报错,则需要执行以下操作
1.管理员身份打开powerShell
2.输入set-ExecutionPolicy RemoteSigned
3选择 y 回车,再次尝试即可