Cherry Documentation

Cherry Documentation

  • Docs
  • Help
  • Blog

›Views & Server response

Getting Started

  • Overview
  • Installation
  • Create a server
  • Adding routes
  • What's next ?

Routing

  • Public resources
  • Basic routes
  • Route contexts
  • Middlewares
  • Redirections

Views & Server response

  • Default error pages
  • Render a html view
  • Render a json payload
  • Download response

Plugins

  • Overview
  • View rendering plugins
  • ORM Plugins
  • Request Plugins
  • Create your own plugins

Miscellaneous features

  • Hooks
  • Server Config
  • Coming Soon...

Best Practices

  • Best Practices

Render a json payload

You want to create an API ? You need to return some json ? Yeah, you could do it by yourself with the response object, but what about circular JSON for example ?

Like for the HTML in the previous chapter, an helper is added to the response object, it works the same way, but unlike the HTML built-in process, you don't have any plugin to install for advance features.

Here are the options available in the configuration parameter :

KeyTypeDescriptionDefault value
headersobjectThe headers bound to the response{ 'Content-Type': 'application/json' }
statusCodenumberThe status code of the response200
serializerfunctionA method call to format the valuesnull
indentnumberThe number of spaces used by indentation2

For the serialization, the library json-stringify-safe is used. If by any chance you already have a json string, you can still provide it to the method, but it won't be modified.

Here are some examples (to use in a route callback of course) :

response.json({
  foo: 'bar'
})

/*
 * Returns a response with the status code 200 like this :
 * {
 *   "foo": "bar"
 * }
 */

 // -------

response.json([
  1,
  2,
  'foo'
], {
  ident: 4,
  statusCode: 400,
  headers: {
    'Content-Type': 'text/plain'
  }
})

/*
 * Returns a response with the status code 400 with the header "Content-Type" as "text/plain" like this :
 * [
 *     1,
 *     2,
 *     "foo"
 * ]
 */

 // -------

const jsonString = JSON.stringify({ test: 'Hello' })
response.json(jsonString)

/*
 * Returns a response with the status code 200 like this :
 * { "test": "Hello" }
 */

As you can see, there is nothing hard about it. Let's code your APIs !

Future improvement possible : Add an option to replace the [Circular] wording, the library json-stringify-safe provides this feature some why not

← Render a html viewDownload response →
Cherry Documentation
Docs
Getting StartedGuides (TODO)API Reference (TODO)
Community
User Showcase (TODO)Project ChatTwitter
More
BlogGitHubStar
Copyright © 2020 Lund-Org