Skip to main content
Module

x/opine/mod.ts>OpineResponse

Minimalist web framework for Deno ported from ExpressJS.
Latest
interface OpineResponse
implements [Opine.Response]
import { type OpineResponse } from "https://deno.land/x/opine@2.3.4/mod.ts";

Type Parameters

optional
ResBody = any

Properties

optional
status: number
optional
statusText: string
optional
headers: Headers
optional
body:
| Uint8Array
| string
optional
req: OpineRequest
locals: any
optional
statusMessage: any
written: boolean

Boolean signifying whether the request has already been responded to.

json: Send<ResBody, this>

Send JSON response.

Examples:

res.json(null);
res.json({ user: 'deno' });
res.setStatus(500).json('oh noes!');
res.setStatus(404).json(`I don't have that`);
jsonp: Send<ResBody, this>

Send JSON response with JSONP callback support.

Examples:

res.jsonp(null);
res.jsonp({ user: 'deno' });
res.setStatus(500).jsonp('oh noes!');
res.setStatus(404).jsonp(`I don't have that`);
send: Send<ResBody, this>

Send a response.

Examples:

res.send(new Buffer('wahoo'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.setStatus(404).send('Sorry, cant find that');

Methods

addResource(rid: number): void

Add a resource ID to the list of resources to be closed after the .end() method has been called.

append(field: string, value: string | string[]): this

Appends the specified value to the HTTP response header field. If the header is not already set, it creates the header with the specified value. The value parameter can be a string or an array.

Example:

res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); res.append('Warning', '199 Miscellaneous warning'); res.append("cache-control", ["public", "max-age=604800", "immutable"]);

Note: calling res.set() after res.append() will reset the previously-set header value.

attachment(filename?: string): this

Set Content-Disposition header to attachment with optional filename.

clearCookie(name: string, options?: CookieOptions): this

Clear cookie by name.

clearCookie(cookie: CookieWithOptionalValue): this

Clear the provided cookie.

download(path: string): Promise<this | void>

Transfer the file at the given path as an attachment.

Optionally providing an alternate attachment filename.

Optionally providing an options object to use with res.sendFile().

This function will set the Content-Disposition header, overriding any existing Content-Disposition header in order to set the attachment and filename.

This method uses res.sendFile().

download(path: string, filename: string): Promise<this | void>
download(
path: string,
filename: string,
options: any,
): Promise<this | void>
etag(chunk: string | Uint8Array | Deno.FileInfo): this

Sets an ETag header.

end(): Promise<void>

Ends a response.

Generally it is recommended to use the res.send() or res.json() methods which will handle automatically setting the Content-Type header, and are able to gracefully handle a greater range of body inputs.

Examples:

res.end();
res.end('<p>some html</p>');
res.setStatus(404).end('Sorry, cant find that');
end(body: DenoResponseBody): Promise<void>
format(obj: any): this

Respond to the Acceptable formats using an obj of mime-type callbacks.

This method uses req.accepted, an array of acceptable types ordered by their quality values. When "Accept" is not present the first callback is invoked, otherwise the first match is used. When no match is performed the server responds with 406 "Not Acceptable".

Content-Type is set for you, however if you choose you may alter this within the callback using res.type() or res.set('Content-Type', ...).

res.format({ 'text/plain': function(){ res.send('hey'); },

 'text/html': function(){
   res.send('<p>hey</p>');
 },

 'application/json': function(){
   res.send({ message: 'hey' });
 }

});

In addition to canonicalized MIME types you may also use extnames mapped to these types:

res.format({ text: function(){ res.send('hey'); },

 html: function(){
   res.send('<p>hey</p>');
 },

 json: function(){
   res.send({ message: 'hey' });
 }

});

By default Express passes an Error with a .status of 406 to next(err) if a match is not made. If you provide a .default callback it will be invoked instead.

get(field: string): string

Get value for header field.

location(url: string): this

Set the location header to url.

The given url can also be the name of a mapped url, for example by default express supports "back" which redirects to the Referrer or Referer headers or "/".

Examples:

res.location('/foo/bar').; res.location('http://example.com'); res.location('../login'); // /blog/post/1 -> /blog/login

Mounting:

When an application is mounted and res.location() is given a path that does not lead with "/" it becomes relative to the mount-point. For example if the application is mounted at "/blog", the following would become "/blog/login".

 res.location('login');

While the leading slash would result in a location of "/login":

 res.location('/login');
redirect(url: string): void

Redirect to the given url with optional response status defaulting to 302.

The resulting url is determined by res.location().

Examples:

res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com'); res.redirect('../login'); // /blog/post/1 -> /blog/login

redirect(code: Status, url: string): void
removeHeader(field: string): this

Remove a header from the response

Examples:

res.removeHeader('Accept');
render(
view: string,
options?: Record<string, unknown>,
callback?: (err: Error, html: string) => void,
): void

Render view with the given options and optional callback fn. When a callback function is given a response will not be made automatically, otherwise a response of 200 and text/html is given.

Options:

  • cache boolean hinting to the engine it should cache
  • filename filename of the view being rendered
render(view: string, callback?: (err: Error, html: string) => void): void
sendFile(path: string, options?: any): Promise<this | void>

Transfer the file at the given path.

Automatically sets the Content-Type response header field.

Examples:

The following example illustrates how res.sendFile() may be used as an alternative for the static() middleware for dynamic situations. The code backing res.sendFile() is actually the same code, so HTTP cache support etc is identical.

app.get('/user/:uid/photos/:file', function(req, res){
  const uid = req.params.uid;
  const file = req.params.file;

  req.user.mayViewFilesFrom(uid, function(yes) {
    if (yes) {
      res.sendFile('/uploads/' + uid + '/' + file);
    } else {
      res.send(403, 'Sorry! you cant see that.');
    }
  });
});
sendStatus(code: Status): this

Set the response HTTP status code to statusCode and send its string representation as the response body.

Examples:

res.sendStatus(200); // equivalent to res.setStatus(200).send('OK') res.sendStatus(403); // equivalent to res.setStatus(403).send('Forbidden') res.sendStatus(404); // equivalent to res.setStatus(404).send('Not Found') res.sendStatus(500); // equivalent to res.setStatus(500).send('Internal Server Error')

set(field: string, value: string): this

Set header field to val, or pass an object of header fields.

Examples:

res.set('Accept', 'application/json');
res.set({
  'Accept-Language': en-US, en;q=0.5,
  'Accept': 'text/html',
});
set(obj: Record<string, string>): this
setHeader(field: string, value: string): this

Set header field to value, or pass an object of header fields.

alias for res.set()

Examples:

res.setHeader('Accept', 'application/json');
res.setHeader({
  'Accept-Language': "en-US, en;q=0.5",
  'Accept': 'text/html',
});
setHeader(obj: Record<string, string>): this
setStatus(code: Status): this

Set status code.

type(type: string): this

Set Content-Type response header with type.

Examples:

res.type('.html');
res.type('html');
res.type('json');
res.type('application/json');
res.type('png');
unset(field: string): this

Removes the header field.

Examples:

res.unset('Accept');

vary(field: string): this

Adds the field to the Vary response header, if it is not there already. Examples:

res.vary('User-Agent').render('docs');