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

Serving our production build

We can serve our production build of the front end through Express.js. This approach is not great for development purposes but is useful for testing the build process and seeing how our live application will act.

Again, replace the previous routing example with the following:

import path from 'path';

const root = path.join(__dirname, '../../');

app.use('/', express.static(path.join(root, 'dist/client')));
app.use('/uploads', express.static(path.join(root, 'uploads')));
app.get('/', (req, res) => {
res.sendFile(path.join(root, '/dist/client/index.html'));
});

The path module offers many functionalities for working with the directory structures.

We use the global __dirname variable to get our project's root directory. The variable holds the path of the current file. Using path.join with ../../ and __dirname gives us the real root of our project.

Express.js provides the use function which runs a series of commands when a given path matches. When executing this function without a path, it is executed for every request.

We use this feature to serve our static files (the avatar images) with express.static. They include bundle.js and bundle.css, created by npm run client:build.

In our case, we first pass '/' with express.static following it. The result of this is that all files and folders in dist are served beginning with '/'. Other paths in the first parameter of app.use, such as '/example', would lead to the result that our bundle.js would be downloadable under '/example/bundle.js' instead.

For example, all avatar images are served under '/uploads/'.

We are now prepared to let the client download all necessary files. The initial route for our client is '/' specified by app.get. The response to this path is index.html. We run res.sendFile and the file path to return this file—that is all we have to do here.

Be sure to execute npm run client:build first. Otherwise, you will receive an error message that these files were not found. Furthermore, when running npm run client, the dist folder is deleted, so you have to rerun the build process.

Refreshing the browser now presents you with the post feed and form from Chapter 1, Preparing Your Development Environment.

The next section focuses on the great functionality of middleware functions in Express.js.

主站蜘蛛池模板: 梅河口市| 武清区| 灵川县| 长沙市| 汝城县| 盐津县| 台北市| 西宁市| 常宁市| 南和县| 彰化市| 平昌县| 胶州市| 周宁县| 武夷山市| 师宗县| 淮阳县| 通州区| 洪江市| 平山县| 盱眙县| 永登县| 河北区| 蒙山县| 林周县| 泰顺县| 仁化县| 汶上县| 麟游县| 长阳| 万全县| 呼玛县| 齐齐哈尔市| 黎川县| 宜城市| 沂源县| 泸定县| 沈阳市| 陇西县| 丹巴县| 辉南县|