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

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.

主站蜘蛛池模板: 宝应县| 翁牛特旗| 军事| 临泽县| 嘉祥县| 苗栗市| 白水县| 红桥区| 宁乡县| 丹巴县| 白山市| 宜兰市| 宜兰县| 凉城县| 平罗县| 米泉市| 永宁县| 千阳县| 广平县| 景泰县| 迁西县| 木兰县| 杭锦旗| 濉溪县| 科技| 南昌市| 陵川县| 合作市| 同江市| 成安县| 招远市| 波密县| 肇州县| 泰顺县| 岳普湖县| 长泰县| 郴州市| 叶城县| 广宗县| 苏州市| 乐清市|