- handling forms in express
<form method="POST" action="/submit-form">
<input type="text" name="username" />
<input type="submit" />
</form>
When the user press the submit button , the browser will automatically make a POST
request to the /submit-form
URL on the same origin of the page, sending the data it contains, encoded as application/x-www-form-urlencoded
. In this case, the form data contains the usename
input field value.
To extract it, you will use the express.urlencoded()
middleware, provided by Express:
const express = require('express')
const app = express()
app.use(express.urlencoded())
Now you need to create a POST
endpoint on the /submit-form
route, and any data will be available on Request.body
:
app.post('/submit-form', (req, res) => {
const username = req.body.username;
res.end()
})
Don’t forget to validate the data before using it, using express-validator
.
- Node, the difference between development and production
You can have different configurations for production and development environments.
Node assumes it’s always running in a development environment. You can signal Node.js that you are running in production by setting the NODE_ENV=production
environment variable.
This is usually done by executing the common
export NODE_ENV=production
Setting the environment to production
generally ensures that
logging is kept to a minimum, essential level
more caching levels take place to optimize performance.
Express provides configurations hooks specific to the environment, which are automatically called based on the NODE_ENV variable value:
app.configure('development', () => {
// ...
})
app.configure('production', () => {
// ...
})
app.configure('production', 'staging', () => {
// ...
})
For example you can use this to set different error handlers for different mode:
app.configure('development', () => {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', () =>{
app.use(express.errorHandler());
});
- Manage cookies with express
Use the Response.cookie()
method to manipulate your cookies.
Examples:
res.cookie('username', 'Flavio')
This method accepts a third parameter which contains various options:
res.cookie('username', 'Flavio', {
domain: '.yuque.com',
path: '/administrator',
secure: true
});
res.cookie('username', 'Flavio', {
expires: new Date(Date.now() + 900000),
httpOnly: true,
});
The most useful parameters you can set are:
Value | Description |
---|---|
domain | the cookie domain name |
expires | set the cookie expiration date. If missing, or 0, the cookie is a session cookie. |
httpOnly | set the cookie to be accessible only by the web server. see HttpOnly |
maxAge | set the expiry time relative to the current time, expressed in milliseconds. |
path | the cookie path. Defaults to / |
secure | Marks the cookie HTTPS only |
signed | set the cookie to be signed |
sameSite | Value of SameSite |
A cookie can be cleared with
res.clearCookie('username')