Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # EventSource [![Build Status](https://secure.travis-ci.org/aslakhellesoy/eventsource-node.png)](http://travis-ci.org/aslakhellesoy/eventsource-node) [![Dependencies](https://david-dm.org/aslakhellesoy/eventsource-node.png)](https://david-dm.org/aslakhellesoy/eventsource-node) [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/aslakhellesoy/eventsource-node/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
  2. [![NPM](https://nodei.co/npm/eventsource.png?stars&downloads)](https://nodei.co/npm/eventsource/)
  3. [![NPM](https://nodei.co/npm-dl/eventsource.png)](https://nodei.co/npm/eventsource/)
  4. This library implements the [EventSource](http://dev.w3.org/html5/eventsource/) client for Node.js. The API aims to be W3C compatible.
  5. ## Install
  6. npm install eventsource
  7. ## Usage
  8. ```javascript
  9. var EventSource = require('eventsource');
  10. var es = new EventSource('http://demo-eventsource.rhcloud.com/');
  11. es.onmessage = function(e) {
  12. console.log(e.data);
  13. };
  14. es.onerror = function() {
  15. console.log('ERROR!');
  16. };
  17. ```
  18. See the [spec](http://dev.w3.org/html5/eventsource/) for API docs.
  19. ## Example
  20. See https://github.com/einaros/sse-example
  21. ## Extensions to the W3C API
  22. ### Setting HTTP request headers
  23. You can define custom HTTP headers for the initial HTTP request. This can be useful for e.g. sending cookies
  24. or to specify an initial `Last-Event-ID` value.
  25. HTTP headers are defined by assigning a `headers` attribute to the optional `eventSourceInitDict` argument:
  26. ```javascript
  27. var eventSourceInitDict = {headers: {'Cookie': 'test=test'}};
  28. var es = new EventSource(url, eventSourceInitDict);
  29. ```
  30. ### Allow unauthorized HTTPS requests
  31. By default, https requests that cannot be authorized will cause connection to fail and an exception
  32. to be emitted. You can override this behaviour:
  33. ```javascript
  34. var eventSourceInitDict = {rejectUnauthorized: false};
  35. var es = new EventSource(url, eventSourceInitDict);
  36. ```
  37. Note that for Node.js < v0.10.x this option has no effect - unauthorized HTTPS requests are *always* allowed.
  38. ### HTTP status code on error events
  39. Unauthorized and redirect error status codes (for example 401, 403, 301, 307) are available in the `status` property in the error event.
  40. ```javascript
  41. es.onerror = function (err) {
  42. if (err) {
  43. if (err.status === 401 || err.status === 403) {
  44. console.log('not authorized');
  45. }
  46. }
  47. };
  48. ```