Skip to content
Andrew Teologov edited this page Jul 10, 2017 · 9 revisions

Teo.JS ResContext object is an extended http.ServerResponse (res) object, which is received as a second argument of the route handler.

API

json(body::*)

Sends a stringified object with correct content type

send()

res.rend method is a multipurpose method for sending the response. It understands the different order of arguments. It sets for you a correct Content-Type(if it wasn't provided), and a Content-Length headers. Also, it sets a default response code to 200. You can pass even a buffer or a stream as a response body.

Supported order of arguments

res.send(body::*)

Accepts body as a first argument. It can be a string, object, buffer, stream. In the case of an object, it will set an application/json header and will respond with a JSON object.

res.send(statusCode::Integer)

Responds with a provided status code. The response body will be set automatically based on a given code. I.e. "OK" for 200 code etc.

res.send(statusCode::Integer, body::*)

Responds with a provided status code, and body.

res.send(statusCode::Integer, body::*, contentType::String)

Responds with a provided status code, and body. Also, sets a Content-Type header. There is no need to pass full content type string. E.g. you can just pass "json", and it will match a correct content type name based on this.

How Content-Type is set inside res.send method?

It can be detected in next ways:

  • Based on Accept header from the request.
  • Based on the extension from the URL. I.e. /my/action.json extension will be parsed as json, and then MIME type will be set to application/json automatically.
  • If an object was passed to res.send method, then application/json will be set.
  • Otherwise, if MIME type is not found, content-type header will be set to application/octet-stream as a default.

Default response format using res.send

// res.send({myVal: "1"}) // it will be sent as a JSON in next format:
{
    code: 200,                   // response code
    data: "{"myVal":1}",         // response body
    message: "OK"            // response message, based on http.STATUS_CODES object
}

Sending an error with res.send

res.send(500, "My custom error message");

Send only a response code. Response body will be matched from http.STATUS_CODES object.

res.send(500);

Clone this wiki locally