JavaScript获取服务端数据的几种方式

ajax

ajax可以通过异步的方式和服务端交换数据,优点:浏览器支持性好,缺点:不支持服务端推送数据

1
2
3
4
5
6
7
8
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/api/user/list", true);
xhttp.send();

fetch

fetch接口返回Promise对象,可以更方便的操作Request、Response、Header对象

1
2
3
4
5
6
7
8
9
10
11
fetch("/api/user/list")
.then(resp => {
var headers = resp.headers;
for (let key of headers.keys()) {
console.log(key + ":" + headers.get(key))
}
return resp.text();
})
.then(data => {
console.log(data);
})

websocket

websocket支持双向通信,保持和服务器连接,实时性强

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var ws = null;
ws = new WebSocket("ws://127.0.0.1/api/ws");
ws.onerror = function(evt) {
console.log('出现错误')
ws = null;
}
ws.onopen = function() {
console.log('已连接')
}
ws.onmessage = function(evt) {
console.log('收到数据:' + evt.data)
}
ws.onclose = function() {
console.log('已关闭')
ws = null;
}
ws.send(msg)

eventsource

eventsource仅支持服务端向客户端推送数据

1
2
3
4
5
6
7
8
9
10
11
12
13
var eventSource = new EventSource('/api/sse/start');
eventSource.addEventListener('message', function(e) {
console.log(e.data);
});

eventSource.addEventListener('open', function(e) {
console.log("Connection was opened.");
}, false);

eventSource.addEventListener('error', function(e) {
eventSource.close();
console.log("error");
}, false);

webrtc

TODO

nginx 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
location / {
root /mnt/d/idea_ce/js-get-data/web;
index index.html;
}

location /api/ {
proxy_set_header Host $host;
proxy_set_header X-Real-Ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://127.0.0.1:8080/;
}

location /api/ws {
proxy_pass http://127.0.0.1:8080/ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
}

参考:

代码地址: https://github.com/tianyl1984/js-get-data

https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html