Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.79 MB, 334 trang )
'number_value': 8476
}
res.json(info);
// or
/* res.send(JSON.stringify({
string_value: 'StackOverflow',
number_value: 8476
})) */
//you can add a status code to the json response
/* res.status(200).json(info) */
})
app.listen(port, function() {
console.log('Node.js listening on port ' + port)
})
On http://localhost:8080/ output object
{
string_value: "StackOverflow",
number_value: 8476
}
Section 3.6: Serving static files
When building a webserver with Express it's often required to serve a combination of dynamic content and static
files.
For example, you may have index.html and script.js which are static files kept in the file system.
It is common to use folder named 'public' to have static files. In this case the folder structure may look like:
project root
├── server.js
├── package.json
└── public
├── index.html
└── script.js
This is how to configure Express to serve static files:
const express = require('express');
const app = express();
app.use(express.static('public'));
Note: once the folder is configured, index.html, script.js and all the files in the "public" folder will be available in at
the root path (you must not specify /public/ in the url). This is because, express looks up for the files relative to the
static folder configured. You can specify virtual path prefix as shown below:
app.use('/static', express.static('public'));
will make the resources available under the /static/ prefix.
Multiple folders
GoalKicker.com – Node.js Notes for Professionals
35
It is possible to define multiple folders at the same time:
app.use(express.static('public'));
app.use(express.static('images'));
app.use(express.static('files'));
When serving the resources Express will examine the folder in definition order. In case of files with the same name,
the one in the first matching folder will be served.
Section 3.7: Adding Middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the
next middleware function in the application’s request-response cycle.
Middleware functions can execute any code, make changes to res and req objects, end response cycle and call next
middleware.
Very common example of middleware is cors module. To add CORS support, simply install it, require it and put this
line:
app.use(cors());
before any routers or routing functions.
Section 3.8: Error Handling
Basic Error Handling
By default, Express will look for an 'error' view in the /views directory to render. Simply create the 'error' view and
place it in the views directory to handle errors. Errors are written with the error message, status and stack trace, for
example:
views/error.pug
html
body
h1= message
h2= error.status
p= error.stack
Advanced Error Handling
Define your error-handling middleware functions at the very end of the middleware function stack. These have four
arguments instead of three (err, req, res, next) for example:
app.js
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
//pass error to the next matching route.
next(err);
});
GoalKicker.com – Node.js Notes for Professionals
36
// handle error, print stacktrace
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
You can define several error-handling middleware functions, just as you would with regular middleware functions.
Section 3.9: Getting info from the request
To get info from the requesting url (notice that req is the request object in the handler function of routes). Consider
this route definition /settings/:user_id and this particular example /settings/32135?field=name
// get the full path
req.originalUrl // => /settings/32135?field=name
// get the user_id param
req.params.user_id // => 32135
// get the query value of the field
req.query.field // => 'name'
You can also get headers of the request, like this
req.get('Content-Type')
// "text/plain"
To simplify getting other info you can use middlewares. For example, to get the body info of the request, you can
use the body-parser middleware, which will transform raw request body into usable format.
var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
Now suppose a request like this
PUT /settings/32135
{
"name": "Peter"
}
You can access the posted name like this
req.body.name
// "Peter"
In a similar way, you can access cookies from the request, you also need a middleware like cookie-parser
req.cookies.name
GoalKicker.com – Node.js Notes for Professionals
37
Section 3.10: Error handling in Express
In Express, you can define unified error handler for handling errors occurred in application. Define then handler at
the end of all routes and logic code.
Example
var express = require('express');
var app = express();
//GET /names/john
app.get('/names/:name', function(req, res, next){
if (req.params.name == 'john'){
return res.send('Valid Name');
} else{
next(new Error('Not valid name'));
//pass to error handler
}
});
//error handler
app.use(function(err, req, res, next){
console.log(err.stack);
// e.g., Not valid name
return res.status(500).send('Internal Server Occurred');
});
app.listen(3000);
Section 3.11: Hook: How to execute code before any req and
after any res
app.use() and middleware can be used for "before" and a combination of the close and finish events can be used
for "after".
app.use(function (req, res, next) {
function afterResponse() {
res.removeListener('finish', afterResponse);
res.removeListener('close', afterResponse);
// actions after response
}
res.on('finish', afterResponse);
res.on('close', afterResponse);
// action before request
// eventually calling `next()`
next();
});
...
app.use(app.router);
An example of this is the logger middleware, which will append to the log after the response by default.
Just make sure this "middleware" is used before app.router as order does matter.
Original post is here
GoalKicker.com – Node.js Notes for Professionals
38