I was exploring developing in Node.JS and found ExpressJS and RailwayJS (based on Express) which are frameworks for Node. The templating engine used Jade/EJS appears to be more for HTML. How might I generate JSON, eg. when I develop an API
Express doesn't automatically parse the HTTP request body for you, but it does have an officially supported middleware package for parsing HTTP request bodies. As of v4. 16.0, Express comes with a built-in JSON request body parsing middleware that's good enough for most JavaScript apps.
json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.
You just create normal JavaScript objects, for example:
var x = {
test: 1,
embedded: {
attr1: 'attr',
attr2: false
}
};
and
JSON.stringify(x);
turns it into JSON string. Note that x
may contain functions which will be omitted. Also JSON.stringify
returns x.toJSON()
if .toJSON()
is available.
Express and Railway both extend off the HTTP module in node and both provide a "response" object as the second argument of the route/middleware handler's callback. This argument's name is usually shortened to res
to save a few keystrokes.
To easily send an object as a JSON message, Express exposes the following method:
res.json({ some: "object literal" });
app.use(function (req, res, next) {
res.json({ some: "object literal" });
});
// -- OR -- //
app.get('/', function (req, res, next) {
res.json({ some: "object literal" });
});
Check out the docs at expressjs.com and the github source is well documented as well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With