官术网_书友最值得收藏!

Returning a response

Our server accepts requests, does some stuff, and finally, sends the response to the client's browser. This can be HTML, JSON, XML, or binary data, among others. As we know, by default, every middleware in Express accepts two objects, request and response. The response object has methods that we can use to send an answer to the client. Every response should have a proper content type or length. Express simplifies the process by providing functions to set HTTP headers and sending content to the browser. In most cases, we will use the .send method, as follows:

res.send("simple text");

When we pass a string, the framework sets the Content-Type header to text/html. It's great to know that if we pass an object or array, the content type is application/json. If we develop an API, the response status code is probably going to be important for us. With Express, we are able to set it like in the following code snippet:

res.send(404, 'Sorry, we cannot find that!');

It's even possible to respond with a file from our hard disk. If we don't use the framework, we will need to read the file, set the correct HTTP headers, and send the content. However, Express offers the .sendfile method, which wraps all these operations as follows:

res.sendfile(__dirname + "/images/photo.jpg");

Again, the content type is set automatically; this time it is based on the filename's extension.

When building websites or applications with a user interface, we normally need to serve an HTML. Sure, we can write it manually in JavaScript, but it's good practice to use a template engine. This means we save everything in external files and the engine reads the markup from there. It populates them with some data and, at the end, provides ready-to-show content. In Express, the whole process is summarized in one method, .render. However, to work properly, we have to instruct the framework regarding which template engine to use. We already talked about this in the beginning of this chapter. The following two lines of code, set the path to our views and the template engine:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

Let's say we have the following template (/views/index.jade):

h1= title
p Welcome to #{title}

Express provides a method to serve templates. It accepts the path to the template, the data to be applied, and a callback. To render the previous template, we should use the following code:

res.render("index", {title: "Page title here"});

The HTML produced looks as follows:

<h1>Page title here</h1><p>Welcome to Page title here</p>

If we pass a third parameter, function, we will have access to the generated HTML. However, it will not be sent as a response to the browser.

主站蜘蛛池模板: 东城区| 安宁市| 通许县| 紫阳县| 岢岚县| 旬阳县| 长沙县| 永福县| 阿瓦提县| 夏邑县| 吉木萨尔县| 恩平市| 大同市| 灵武市| 南澳县| 日喀则市| 孟州市| 大洼县| 德惠市| 姜堰市| 济南市| 东城区| 安福县| 贵溪市| 塔河县| 湘乡市| 吉林省| 讷河市| 永昌县| 长丰县| 洪洞县| 大港区| 绵竹市| 安西县| 大冶市| 和田县| 聂拉木县| 文山县| 阿勒泰市| 盘山县| 曲麻莱县|