Host static resources

  1. express.static()

    express.static() can be very convenient to create a static resource server. It can specify a directory to be hosted as a static resource folder, and can access all files under the directory folder.

    For example, the images, CSS files, and JS files in the public directory can be opened to the outside world through the following code.

    1
    app.use(express.static('./public')) //Write the folder path, such as ./clock. If not, write the absolute path.

    Once configured, you can access all files in the public directory:

    Note: Express looks for files in the specified static directory, and provides access paths to resources. However, the name of the directory where static files are stored (eg public) will not appear in the URL.


  2. Hosting multiple static resource directories

    To host multiple static resource directories, call express.static() multiple times. When accessing static resource files, the express.static() function will look for the required files according to the order in which the directories are added (for example, both folders have index.html, which is written in front. After the first folder finds the file will not look back).

    1
    2
    app.use(express.static('./public'))
    app.use(express.static('./files'))

  1. Mounted path prefix

    If you want to mount the path prefix before the hosted static resource access path, you can use the following methods.

    1
    app.use('/public', express.static('public'))

    Once configured, you can access files in the public directory through addresses with a /public prefix:


Share