Input : Http server input

更新时间:
2024-05-13
下载文档

Input : Http server input

HttpInput is the base calss of HttpClientResponse and HttpServerRequest.

The client obtains the http response message through the input object. The server obtains the request information sent by the client through the input object.

HttpInput inherits from the Readable stream class and can easily use the pipe API to transport streams.

Support

The following shows HttpInput module APIs available for each permissions.

 User ModePrivilege Mode
input.url
input.host
input.method
input.protocol
input.statusCode
input.headers
input.header
input.xhr
input.body
input.enableCache
input.abort
input.ip
input.peerName
input.sockName
input.destroy
input.pipe
input.unpipe
input.connected

HttpOutput Object

input.url [for REQUEST]

  • {String} HTTP request url.

Example

console.log(input.url);
// /index.html?name=xiaoming&age=22

input.host [for REQUEST]

  • {String} HTTP request host (from header 'host' content).

Example

// http://192.168.7.2:8080/index.html
console.log(input.host);
// 192.168.7.2:8080

input.method [for REQUEST]

  • {String} Contains a string corresponding to the HTTP method of the request. It is expressed in uppercase and is case sensitive.

The method support:

DELETE, GET, HEAD, POST, PUT CONNECT, OPTIONS, TRACE COPY, LOCK, MKCOL, MOVE, PROPFIND, PROPPATCH, SEARCH, UNLOCK, BIND, REBIND, UNBIND, ACL REPORT, MKACTIVITY, CHECKOUT, MERGE MSEARCH, NOTIFY

input.statusCode [for RESPONSE]

  • {Integer} HTTP response status.

Status code:

StatusMessage
100Continue
101Switching Protocols
200OK
201Created
202Accepted
203Non-Authoritative Information
204No Content
205Reset Content
206Partial Content
300Multiple Choices
301Moved Permanently
302Found
303See Other
304Not Modified
305Use Proxy
307Temporary Redirect
400Bad Request
401Unauthorized
402Payment Required
403Forbidden
404Not Found
405Method Not Allowed
406Not Acceptable
407Proxy Authentication Required
408Request Timeout
409Conflict
410Gone
411Length Required
412Precondition Failed
413Payload Too Large
414URI Too Large
415Unsupported Media Type
416Range Not Satisfiable
417Expectation Failed
426Upgrade Required
500Internal Server Error
501Not Implemented
502Bad Gateway
503Service Unavailable
504Gateway Time-out
505HTTP Version Not Supported

input.protocol [for REQUEST]

  • {String} HTTP request protocol.

Example

console.log(input.protocol);
// http or https

This property is supported in EdgerOS 1.10.1 and later.

input.statusMessage [for RESPONSE]

  • {String} HTTP response status message. See input.statusCode.

input.headers

  • {Object} HTTP headers.

Example

console.log(input.headers.host);
// => 192.168.7.32:8000
console.log(input.headers['accept-language']); 
// => zh-CN,zh;q=0.8

input.header(key)

  • key {String} Header key.
  • Returns: {String} Header value.

Example

console.log(input.getHeader('Host'));

input.xhr [for REQUEST]

  • {Boolean} If HTTP header X-Requested-With exist.

A Boolean property that is true if the request’s X-Requested-With header field is XMLHttpRequest, indicating that the request was issued by a client library such as jQuery.

Example

console.log(input.xhr);
// => true

input.body

  • {Object | Buffer | String} Request body, default: {}.

If enableCache() is set, input data will be stored in input.body in Buffer type. If enableCache() is not set or input data is empty, then input.body remains {} . See input.enableCache().

input.enableCache(cache)

  • cache {Boolean} Enable cache or not, default: true.

If enableCache(true) is set, the input data will be stored in input.body in Buffer type when input receives data.

enableCache(false)meens empty the cache.

Example

  • Collect data from data events
var http = require('http');

http.request('http://192.168.7.32:8000/get', function(res) {
  var data = [];
  res.on('data', (buf) => {
    data.push(buf);
  });

  res.on('end', () => {
    data = Buffer.concat(data);
    var str = data.toString();
    console.log(`receive body: ${str}`);
  });
});
  • Cache data to body:
var http = require('http');

http.request('http://192.168.7.32:8000/get', function(res) {
  res.enableCache();
  res.on('end', () => {
    console.log('get recv data:', res.body.toString());
  });
});

input.abort()

If the data reception is not completed or is not aborted, the input data is aborted. The ‘aborted` event is fired when this operation is active.

In REQUEST mode, if the user replies to the request(write, end ... operator) before the data is received, the receiving process will automatically abort and the 'aborted' event will fire.

Example

var HttpServer = require('http_server');
var socket = require('socket');

var server = HttpServer.createServer('http', handle, 0, socket.sockaddr(socket.INADDR_ANY, 8000));

function handle(req, res) {
  var data = [];
  var len = 0;
  req.on('data', (buf) => {
    len += buf.length;
    if (len > 1024 * 4) {
      req.abort();
    } else {
      data.push(buf);
  }
  });

  req.on('end', () => {
    data = Buffer.concat(data);
    var str = data.toString();
    res.end(`receive body: ${str}`);
  });

  req.on('aborted', () => {
    console.log(`the body is too big`);
    res.status(400);
    res.end();
  });
}

input.ip

  • {String}

Get the IP address of the remote client.

input.peerName()

  • Returns: {Object} Returns remote client address.

Get the address of the remote client, includes following items:

  • domain {Integer} Address domain: socket.AF_INET or socket.AF_INET6.
  • addr {String} Address.
  • port {Integer} Port.

input.sockName()

  • Returns: {Object} Returns my connect address.

Get the address of the my connect.

input.destroy([error])

  • error {Error} which will be passed as payload in 'error' event.
  • Returns: {HttpInput} This object.

When this method closes the readable stream, it also closes the underlying socket connection.

input.pipe(destination[, options])

  • destination {Writable} The destination for writing data.
  • options {Object} Pipe options:
    • end {Boolean} End the writer when the reader ends. default: true.
  • Returns: {Writable} The destination, allowing for a chain of pipes if it is a Duplex stream.

Pipe data from input to writable stream object. More to see readable.pipe.

Example

var HttpServer = require('http_server');
var socket = require('socket');
var iosched = require('iosched');
var WriteStream = require('stream/fs_writestream');

HttpServer.createServer('http', handle, 0, socket.sockaddr(socket.INADDR_ANY, 8000));

function handle(req, res) {
  var wStream = WriteStream.createWriteStream('./tem.tem');

  var finished = false;
  wStream.on('error', (err) => {
    console.error('on write stream error:', err);
    if (finished) {
      return;
    }
    finished = true;
    res.sendStatus(500, err.message);
  });

  req.on('error', (err) => {
    console.error('on req error:', err);
    if (finished) {
      return;
    }
    finished = true;
    wStream.destroy();
    res.sendStatus(500, err.message);
  });

  req.on('end', () => {
    if (finished) {
      return;
    }
    finished = true;
    res.send('ok');
  })

  req.pipe(wStream);
}

iosched.forever();

input.unpipe([destination])

  • destination {Writable} Optional specific stream to unpipe.
  • Returns:{HttpInput} This object.

The input.unpipe() method detaches a Writable stream previously attached using the stream.pipe() method. More to see readable.unpipe.

input.connected()

  • Returns: {Boolean} Whether the current connection is connected.

Get whether the current network connection is connected.

Example

var connected = input.connected();
文档内容是否对您有所帮助?
有帮助
没帮助