express框架与Ajax使用

xhr.readyState 可以用来查看请求当前的状态参考资料
0: 表示 XMLHttpRequest 实例已经生成,但是 open()方法还没有被调用。
1: 表示 send()方法还没有被调用,仍然可以使用 setRequestHeader(),设定 HTTP请求的头信息。
2: 表示 send()方法已经执行,并且头信息和状态码已经收到。
3: 表示正在接收服务器传来的 body 部分的数据。
4: 表示服务器数据已经完全接收,或者本次接收已经失败了

express使用步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    //1.引入express
const { response, request } = require('express');
const express = require('express');
//2.创建对象  
const app = express();
//3.创建url路径
//get
app.get('/service',(request,response)=>{
     response.setHeader('Access-Control-Allow-Origin','*')
    //设置响应  
    response.send('hello express');
});
//post
//创建url路径  
app.post('/service',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*')
   //设置响应  
   response.send('hello express');
});
//4.监听端口 
app.listen(8000,()=>{
    console.log("8000端口服务已经启动。。。。。")
})


Ajax使用步骤
//创建对象  
const xhr = new XMLHttpRequest()
//初始化,设置请求方法 和 url
xhr.open('GET','http://127.0.0.1:8000/service')
//发送  
xhr.send()
//事件绑定 处理服务端返回结果 
xhr.onreadystatechange = function(){
 //readyState是xhr中的属性 表示状态0 1 2 3 4 
    if(xhr.readyState == 4){
         //status是状态码2XX就是成功
           if(xhr.status >= 200 & xhr.status < 300){
                //处理结果 行 头 空行 体  
                //1.响应行 
                console.log(xhr.status) 
                console.log(xhr.statusText)
                console.log(xhr.getAllResponseHeaders)
                console.log(xhr.response)
                text.innerHTML=xhr.response
                   }
                }

1) 创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
2) 设置请求信息
xhr.open(method, url);
//可以设置请求头,一般不设置
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
3) 发送请求
xhr.send(body) //get 请求不传 body 参数,只有 post 请求使用
4) 接收响应
//xhr.responseXML 接收 xml 格式的响应数据
//xhr.responseText 接收文本格式的响应数据
xhr.onreadystatechange = function (){
if(xhr.readyState == 4 && xhr.status == 200){
var text = xhr.responseText;
console.log(text);
}