Use Express and AbsurdJS for Node. js applications (1)
Many new technologies are attracting more and more developers today. Node. js is one of them. Because it is JavaScript-driven, many people are interested in it. In this tutorial, I will teach you how to use AbsurdJS with Express. Express is a popular Node. js framework, while AbsurdJS is fresh. I hope you will find it useful after reading it.
The source code in this article can be downloaded from here.
Introduction
As I mentioned, Express is very popular. Because it is one of the earliest Node. js frameworks. It manages all trivial tasks, such as routing selection, Parameter Parsing, templates, and sending responses to browsers. Its Library is well encapsulated by native Node. js Based on the Middleware Architecture provided by Connect.
AbsurdJS was initially a CSS Preprocessor. The purpose is to provide CSS developers with better flexibility. It accepts pure JavaScript code and converts it to CSS. Everyone gave positive feedback to it, and I am still trying to improve it. Now it can not only pre-process CSS, but also process HTML. It accepts JSON and YAML and is successfully exported as a client.
Procedure
To make the final project run, we need to install Node. js. Open nodejs.org and click the big green "INSTALL" button. After downloading and installing the package, you can call the Node. js script and use the npmNode Package Manager to install the dependency package.
Create a folder for your project and create an empty package. json file. The package manager will start with this file to install the packages we need. We only need two packages, so the json file should look like this:
- {
- "name": "AbsurdJSAndExpress",
- "description": "AbsurdJS + Express app",
- "version": "0.0.1",
- "dependencies": {
- "express": "3.4.4",
- "absurd": "*"
- }
- }
Of course, there are many other parameters that can be configured here, but for the sake of convenience, we should first follow the above configuration. Open the terminal, locate the directory that contains Package. json, and execute:
- npm install
The node_modules folder is generated in the current directory, and Express and AbsurdJS are automatically downloaded.
Running Server
With Express, you only need a few lines of code to run an http server.
- var express = require('express'),
- app = express();
-
- app.listen(3303);
- console.log('Listening on port 3303');
Save the above Code as app. js and run it:
- node app.js
The console displays "Listening on port 3303 ". Open http: // localhost: 3303/in the browser and you will see:
- Cannot GET /
Don't worry, this is normal, because we haven't added a route.
Add route
Express provides a friendly API to define URL routing. Here we simply add one and paste the following code into app. js.
- app.get('/', function(req, res, next) {
- res.setHeader('Content-Type', 'text/html');
- res.send("application");
- });
I have done a few things here .. The first parameter of the get method defines the path. The second parameter is a method used to process the request. It accepts three parameters: request, response, and next. The advantage here is that we can pass in multiple functions, which will be called one by one. All we need to do is execute next (). Otherwise, the next method will not be called. For example:
- app.get(
- '/',
- function(req, res, next) {
- console.log("do some other stuff here");
- next();
- },
- function(req, res, next) {
- res.send("application");
- }
- );
A common practice in routing definition is to add reusable tasks as middleware. For example, we have two types of Content-Type: HTML and CSS. The following method is more flexible.
- var setContentType = function(type) {
- return function(req, res, next) {
- res.setHeader('Content-Type', 'text/' + type);
- next();
- }
- }
- app.get('/', setContentType("html"), function(req, res, next) {
- res.send("application");
- });
To provide CSS, use setContentType ("css.
Provide HTML
Many tutorials and articles on Express introduce some template engines. Usually Jade, Hogan, or Mustache. However, if AbsurdJS is used, we do not need a template engine. We can use JavaScript to compile HTML. Specifically, JavaScript objects are used. Let's start with implementing the landing page. Create a folder pages and create a new landing. js file in it. We are using Node. js, so the file should include:
- module.exports = function(api) {
- // ...
- }
Note that the returned functions are referenced by the AbsurdJS API. This is exactly what we need. Now add HTML:
- module.exports = function(api) {
- api.add({
- _:"<!DOCTYPE html>",
- html: {
- head: {
- 'meta[http-equiv="Content-Type" content="text/html; charset=utf-8"]': {},
- 'link[rel="stylesheet" type="text/css" href="styles.css"]': {}
- },
- body: {}
- }
- });
- }
The string added by the "_" attribute is not converted when it is compiled into HTML. Other attributes define a tag. You can also use other methods to define tag attributes, but I think the above method is better. This idea is obtained from the Emmet plug-in of Sublime. After compilation, the following code is generated:
- <!DOCTYPE html>
-
-
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <link rel="stylesheet" type="text/css" href="styles.css"/>
-
- <body/>
-
This tutorial has only one page, but in reality you may use the same HTML in multiple pages. In this case, it is more reasonable to move this part of code to an external file and reference it as needed. Of course, repeated templates can also be used here. Create a file/pages/partials/layout. js:
- module.exports = function(title) {
- return {
- _:"<!DOCTYPE html>",
- html: {
- head: {
- 'meta[http-equiv="Content-Type" content="text/html; charset=utf-8"]': {},
- 'link[rel="stylesheet" type="text/css" href="styles.css"]': {},
- title: title
- },
- body: {}
- }
- };
- };
This is actually a function that returns objects. Therefore, the previous landing. js can be changed:
- module.exports = function(api) {
- var layout = require("./partials/layout.js")("Home page");
- api.add(layout);
- }
As you can see, the layout template accepts the title variable. In this way, part of the content can be dynamically generated.