aaac7fed
liuqimichale
add
|
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
# EventSource [](http://travis-ci.org/aslakhellesoy/eventsource-node) [](https://david-dm.org/aslakhellesoy/eventsource-node) [](https://bitdeli.com/free "Bitdeli Badge")
[](https://nodei.co/npm/eventsource/)
[](https://nodei.co/npm/eventsource/)
This library implements the [EventSource](http://dev.w3.org/html5/eventsource/) client for Node.js. The API aims to be W3C compatible.
## Install
npm install eventsource
## Usage
```javascript
var EventSource = require('eventsource');
var es = new EventSource('http://demo-eventsource.rhcloud.com/');
es.onmessage = function(e) {
console.log(e.data);
};
es.onerror = function() {
console.log('ERROR!');
};
```
See the [spec](http://dev.w3.org/html5/eventsource/) for API docs.
## Example
See https://github.com/einaros/sse-example
## Extensions to the W3C API
### Setting HTTP request headers
You can define custom HTTP headers for the initial HTTP request. This can be useful for e.g. sending cookies
or to specify an initial `Last-Event-ID` value.
HTTP headers are defined by assigning a `headers` attribute to the optional `eventSourceInitDict` argument:
```javascript
var eventSourceInitDict = {headers: {'Cookie': 'test=test'}};
var es = new EventSource(url, eventSourceInitDict);
```
### Allow unauthorized HTTPS requests
By default, https requests that cannot be authorized will cause connection to fail and an exception
to be emitted. You can override this behaviour:
```javascript
var eventSourceInitDict = {rejectUnauthorized: false};
var es = new EventSource(url, eventSourceInitDict);
```
Note that for Node.js < v0.10.x this option has no effect - unauthorized HTTPS requests are *always* allowed.
### HTTP status code on error events
Unauthorized and redirect error status codes (for example 401, 403, 301, 307) are available in the `status` property in the error event.
```javascript
es.onerror = function (err) {
if (err) {
if (err.status === 401 || err.status === 403) {
console.log('not authorized');
}
}
};
```
|