Basic webserver with node.js and express for serving html file and assets

后端 未结 4 1915
失恋的感觉
失恋的感觉 2021-01-30 06:37

I\'m making some frontend experiments and I\'d like to have a very basic webserver to quickly start a project and serve the files (one index.html file + some css/js/img files).

4条回答
  •  悲哀的现实
    2021-01-30 07:14

    Thank you to original posters, but their answers are a bit outdated now. It's very, very simple to do. A basic setup looks like this:

    const express = require("express");
    const app = express();
    const dir = `${__dirname}/public/`;
    
    app.get("/", (req, res) => {
      res.sendFile(dir + "index.html");
    });
    
    app.get("/contact", (req, res) => {
      res.sendFile(dir + "contact.html");
    });
    
    // Serve a 404 page on all other accessed routes, or redirect to specific page
    app.get("*", (req, res) => {
      //   res.sendFile(dir + "404.html");
      //   res.redirect("/");
    });
    
    app.listen(3000);
    

    The above example is if you want to serve individual HTML files. If you were serving a single page JS app, this would work.

    const express = require("express");
    const app = express();
    const dir = `${__dirname}/public/`;
    
    app.get("*", (req, res) => {
      res.sendFile(dir + "index.html");
    });
    
    app.listen(3000);
    

    If you need to serve other static assets from within a folder, you can add something like this before you start defining the routes:

    app.use(express.static('public'))
    

    Let's say you have a js folder inside public like: public/js. You could include any of those files inside of your html files using relative paths. For example, let's say /contact needs a contact.js file. In your contact.html file, you can include the script as easy as:

    
    

    Building off of that example, you can do the same with css, images etc.

    
    
    

    Hope this helps everyone from the future out.

提交回复
热议问题