Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding contents from Wiki of expressjs:express in en language #1565

Open
wants to merge 8 commits into
base: gh-pages
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions en/3x/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ redirect_from: "/3x/api.html"

<h1>3.x API</h1>

See also:

* [New features in 3.x.](../guide/new-features-in-3x.md)
* [Migrating from 2.x to 3.x.](../guide/migrating-from-2x-to-3x.md)

{% include api/{{ page.lang }}/3x/express.md %}
{% include api/{{ page.lang }}/3x/app.md %}
{% include api/{{ page.lang }}/3x/req.md %}
Expand Down
4 changes: 2 additions & 2 deletions en/guide/migrating-4.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ There are several significant changes in Express 4:

See also:

* [New features in 4.x.](https://github.com/expressjs/express/wiki/New-features-in-4.x)
* [Migrating from 3.x to 4.x.](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
* [New features in 4.x.](./new-features-in-4x.md)
* [Migrating from 3.x to 4.x.](./migrating-from-3.x-to-4.x.md)

<h3 id="core-changes">
Changes to Express core and middleware system
Expand Down
154 changes: 154 additions & 0 deletions en/guide/migrating-from-2x-to-3x.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
---
layout: page
title: Migrating From 2.x to 3.x
menu: guide
lang: en
redirect_from: "/guide/migrating-from-2x-to-3x.html"
---
# Migrating From 2.x to 3.x
## Removed

- `res.render()` "status" option (use node's `res.statusCode=` or `res.status(code).render(...)`)
- `res.render()` "charset" option (use `res.charset=`)
- `res.local(foo, bar)` (use `res.locals.foo = bar` or `res.locals({ foo: bar })` instead)
- `app.dynamicHelpers()` (use middleware + `res.locals`)
- `app.helpers()` (use `app.locals`)
- the concept of a "layout" (template engine specific now)
- `partial()` (template engine specific)
- `res.partial()`
- "view options" setting, use `app.locals`
- "hints" setting
- `req.isXMLHttpRequest` (use `req.xhr`)
- `app.error()` (use middleware with (err, req, res, next))
- `req.flash()` (just use sessions: `req.session.messages = ['foo']` or similar)
- [connect-flash](https://github.com/jaredhanson/connect-flash) can be used as middleware to provide req.flash()
- the `jsonp callback` setting was removed (use `res.jsonp()`)

## Changed

- `req.header(field[, defaultValue])` replaced by `req.get(field)` (remains for backwards compatibility)
- `res.header(field[, value])` replaced by `res.set(field, value)` / `res.get(field)` (remains for backwards compatibility)
- renamed `app.register()` to `app.engine()`
- template engine compliance from `engine.compile(str, options) => Function` to `engine.__express(filename, options, callback)`
- `express.createServer()` is now simply `express()` (but remains for BC).
- Keep in mind that the return value of `express()` is **no longer an `http.Server` instance**. (See the **Application function** section below for more details)

## View options

The "view options" setting is no longer necessary, `app.locals` are the local variables merged with `res.render()`'s, so `app.locals.pretty = true` is the same as passing `res.render(view, { pretty: true })`.

## Application function

The return value of `express()` is a JavaScript `Function`, encapsulating everything that makes an Express app tick. This means you can easily setup HTTP and HTTPS versions of your application by passing it to node's `http.createServer()` and `https.createServer()`:

```js
var app = express();

Check failure on line 45 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Unexpected var, use let or const instead

Check failure on line 45 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Extra semicolon
http.createServer(app).listen(80);

Check failure on line 46 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Extra semicolon
https.createServer(options, app).listen(443);

Check failure on line 47 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Extra semicolon
```

For convenience, and smaller applications the `app.listen()` method takes the same arguments, wrapping in an HTTP server. The following are equivalent:

```js
var app = express();

Check failure on line 53 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Unexpected var, use let or const instead

Check failure on line 53 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Extra semicolon
app.listen(3000);

Check failure on line 54 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Extra semicolon
```

and

```js
var app = express()

Check failure on line 60 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Split initialized 'var' declarations into multiple statements

Check failure on line 60 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

Unexpected var, use let or const instead
, http = require('http');

Check failure on line 61 in en/guide/migrating-from-2x-to-3x.md

View workflow job for this annotation

GitHub Actions / test

',' should be placed last

http.createServer(app).listen(3000);
```

This however means that methods that are on node's `http.Server.prototype` are no longer present on `app`, for example `app.address()` must now be called on the server returned by `app.listen()` or the one you have wrapped with `http.createServer(app)`.

## Socket.IO compatibility

Socket.IO's `.listen()` method takes an `http.Server` instance as an argument. As of 3.x, the return value of `express()` is not an `http.Server` instance. (See the **Application function** section above.) To get Socket.IO working with Express 3.x, make sure you manually create and pass your `http.Server` instance to Socket.IO's `.listen()` method.

```js
var app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);

server.listen(3000);
```

## Template engine integration

Express 2x template engine compatibility required the following module export:

```js
exports.compile = function(templateString, options) {
return a Function;
};
```

Express 3x template engines should export the following:

```js
exports.\_\_express = function(filename, options, callback) {
callback(err, string);
};
```

If a template engine does not expose this method, you're not out of luck, the `app.engine()` method allows you to map any function to an extension. Suppose you had a markdown library and wanted to render `.md` files, but this library did not support Express, your `app.engine()` call may look something like this:

```js
var markdown = require('some-markdown-library');

app.engine('md', function(path, options, fn){
fs.readFile(path, 'utf8', function(err, str){
if (err) return fn(err);
str = markdown.parse(str).toString();
fn(null, str);
});
});
```

## View system changes

By removing the concept of a "layout" & partials in Express 3.x template engines will have greater control over file I/O. This means integration with template engines much easier, and greatly simplify the view system's internals.

This also enables template engines to supply their own means of inheritance, for example later releases of Jade provide Django-inspired template inheritance, where the view being rendered specifies the layout it wants to extend. For an example of this using the Jade engine visit [http://www.devthought.com/code/use-jade-blocks-not-layouts/](http://www.devthought.com/code/use-jade-blocks-not-layouts/)

Post-release we may end up building an Express extension to support the old `partial()` concept.

To get back layout functionality with EJS you can use [express-partials](https://github.com/publicclass/express-partials) or [ejs-locals](https://github.com/RandomEtc/ejs-locals).

## Error handling middleware

The `app.error(callback)` method in 2.x was effectively the same as the following:

```js
app.error = function(fn){
this.use(function(err, req, res, next){
fn.apply(this, arguments);
});
};
```

The reason for this is that Connect differentiates between "regular" middleware, and "error-handling" middleware via the `fn.length`. A regular middleware has a `fn.length` of `<= 3`, aka `(req, res, next)`, whereas error-handling middleware must have exactly `4` `(err, req, res, next)`. So the reason 2.x wrapped this functionality was to simply provide a bit of sugar on-top of this API making the parameters optional.

In short all you need to do to "catch" these errors that are passed along is to define another middleware, but with `4` arguments. Note that this middleware should be defined _below_ all the others, so that they may invoke `next(err)` in order to pass an error to it like so:

```js
app.use(express.bodyParser())
app.use(express.cookieParser())
app.use(express.session())
app.use(app.router) // the router itself (app.get(), app.put() etc)
app.use(function(err, req, res, next){
// if an error occurs Connect will pass it down
// through these "error-handling" middleware
// allowing you to respond however you like
res.send(500, { error: 'Sorry something bad happened!' });
})
```

## App- & Request-level local variables

Do not use `name` as a key in app.locals or res.locals because those objects are Function object instances. Any attempt to set them will be silently ignored. Other unstable or unusable top level keys are listed here: [Function Instance Properties](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function#Function_instance-Properties).
217 changes: 217 additions & 0 deletions en/guide/migrating-from-3.x-to-4.x.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
---
layout: page
title: Migrating from 3.x to 4.x
menu: guide
lang: en
redirect_from: "/guide/migrating-from-3.x-to-4.x.html"
---
# Migrating from 3.x to 4.x

Express 3.x to 4.0 migration guide. You may also be interested in [New features in 4.x][new-in-4x].

See [Express 4.x docs][4x-docs] for more examples and complete API documentation.

## Overview

**Express 4 no longer has Connect as a dependency.** This means that ALL bundled middleware (except `static`) is no longer available on the `express` module. Each middleware is available as a module. (More on this below.)

This change allows middleware to receive fixes, updates, and releases, without impacting Express release cycles (and vice-versa).

**These are not direct replacements. Please read their documentation _before_ blindly using them with old arguments.**

- `bodyParser` [body-parser](https://github.com/expressjs/body-parser)
- `cookieParser` [cookie-parser](https://github.com/expressjs/cookie-parser)
- `favicon` [serve-favicon](https://github.com/expressjs/serve-favicon)
- `session` [express-session](https://github.com/expressjs/session)

Others documented here: [https://github.com/senchalabs/connect#middleware](https://github.com/senchalabs/connect#middleware)

## Removed in Express 4

### `app.configure()`

This method is no longer available.

If you wish to configure different routes based on environment, use either an `if` statement or another module.

```js
app.configure('development', function() {
// configure stuff here
});
// becomes
var env \= process.env.NODE_ENV || 'development';
if ('development' \== env) {
// configure stuff here
}
```

### `app.routes()`

This method is no longer available. See [issue 2049](https://github.com/expressjs/express/issues/2049).

### `app.router`

The middleware stack has been overhauled! This reduces confusion with `.use` vs `.get` (or other HTTP verbs).

As a result, the need to manually do `app.use(app.router)` has been removed. See the Routers section (below) on the new middleware and routing API.

If you had code that looked like this:

```js
app.use(cookieParser());
app.use(bodyParser());
/// .. other middleware .. doesn't matter what
app.use(app.router); // \*\*this line will be removed\*\*

// more middleware (executes after routes)
app.use(function(req, res, next) {});
// error handling middleware
app.use(function(err, req, res, next) {});

app.get('/' ...);
app.post(...);
```

`app.router` has been removed. Middleware and routes are now executed in the order they're added.

Your code should move any calls to `app.use` that came after `app.use(app.router)` after any routes (HTTP verbs).

```js
app.use(cookieParser());
app.use(bodyParser());
/// .. other middleware .. doesn't matter what

app.get('/' ...);
app.post(...);

// more middleware (executes after routes)
app.use(function(req, res, next) {});
// error handling middleware
app.use(function(err, req, res, next) {});
```

### `express.createServer()`

_Long_ deprecated. Just create new apps with `express()`.

### Connect middleware

All Connect middleware lives in separate modules (with the exception of `express.static`, which is provided for convenience). Everything else benefits from being a separate module, with its own versioning.

### Connect's patches

Connect patched Node's prototypes globally. This is considered bad behavior, and was removed in Connect 3.

Some of these patches were:

- `res.on('header')`
- `res.charset`
- `res.headerSent` Uses Node's `res.headersSent` instead
- special handling of `res.setHeader` for `Set-Cookie` header

You should no longer use these in any Connect or Express libraries.

### `res.charset`

If you want Express to set a default charset (and you should!), use `res.set('content-type')` or `res.type()` to set the header.

A default charset will NOT be added when using `res.setHeader()`.

### `res.setHeader('Set-Cookie', val)`

This will no longer implicitly append `val` to the current list of `Set-Cookie` values. You will want to do that manually or use the `res.cookie` method to set cookies, which does this.

## Changed in Express 4

### `app.use`

`app.use` now accepts `:params`.

```js
app.use("/users/:user_id", function (req, res, next) {
// req.params.user_id exists here
});
```

### `req.accepted()`

Use `req.accepts()` instead.

- `req.accepts()`
- `req.acceptsEncodings()`
- `req.acceptsCharsets()`
- `req.acceptsLanguages()`

All use [`accepts`](https://github.com/expressjs/accepts) internally. Please refer to `accepts` for any issues or documentation requests.

**Note:** these properties may have changed from arrays to functions. To continue using them as "arrays", call them without arguments. For example, `req.acceptsLanguages() // => ['en', 'es', 'fr']`.

### `res.location()`

No longer resolves relative URLs. Browsers will handle relative URLs themselves.

### `app.route` → `app.mountpath`

When mounting an Express app in another Express app.

### Changes to Configuration in Express 4

#### `json spaces`

In development, this is no longer enabled by default.

#### `req.params`

Is now an object instead of an array.

This won't break your app if you used the `req.params[##]` style for regexp routes where parameter names are unknown.

#### `res.locals`

Is now an object instead of a function.

#### `res.headerSent`

Changed to `headersSent` to match the Node.js `ServerResponse` object.

You probably never used this, so it probably won't be an issue.

#### `req.is`

Now uses [type-is](https://github.com/expressjs/type-is) internally. Please refer to `type-is` for any issues or documentation requests.

## Added in Express 4

### `app.route(path)`

Returns a new `Route` instance. A `Route` is invoked when a request matching the route `path` is received. Routes can have their own middleware stacks. They also have methods for the HTTP VERBS to process requests.

See the Routes and [Routing docs](http://expressjs.com/4x/api.html#router) for more details on creating routes in Express.

### Router and Route middleware

The Router has been overhauled. It is now a full-fledged middleware router.

The Router is a good way to separate your routes into files/modules—without sacrificing features like parameter matching and middleware.

## Deprecated since 3.x

The following have been deprecated since 4.0 and affect you when upgrading from 3.x to the latest 4.x version. Check the [Changelog](https://github.com/expressjs/express/blob/master/History.md) for the latest changes.

- Deprecate leading `:` in `name` for `app.param(name, fn)`
- Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead
- Deprecate `app.param(fn)`
- deprecate `res.sendfile` -- use `res.sendFile` instead
- deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead
- deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead
- deprecate `res.json(obj, status)` -- use `res.status.json(obj)` instead
- the edge-case `res.json(status, num)` requires `res.status(status).json(num)`
- deprecate `res.jsonp(obj, status)` -- use `res.status(status).jsonp(obj)` instead
- deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead
- deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead
- deprecate things with `depd` module
- deprecate `req.host` -- use `req.hostname` instead
- deprecate `app.del()` -- use `app.delete()` instead

[4x-docs]: http://expressjs.com/4x/api.html
[new-in-4x]: ./new-features-in-4x.md
Loading
Loading