Hogyan telepítheti az alkalmazást az internetre az Express.js és a Heroku használatával

Ha még nem ismeri a webfejlesztés világát, sok időt fog tölteni azzal, hogy megtanulja, hogyan lehet statikus webhelyeket létrehozni HTML, CSS és JavaScript használatával.

Ezután elkezdheti megtanulni a népszerű keretrendszerek, például a React, a VueJS vagy az Angular használatát.

Néhány új ötlet kipróbálása és néhány webhely helyi futtatása után elgondolkodhat azon, hogy miként telepítheti webhelyét vagy alkalmazását. És mint kiderült, néha nehéz lehet tudni, hogy hol kezdjem.

Személy szerint a Heroku-ban tárolt Express kiszolgáló futtatását tartom az egyik legegyszerűbb módnak az induláshoz. Ez a cikk megmutatja, hogyan kell ezt megtenni.

A Heroku egy felhőplatform, amely számos programozási nyelvet és keretet támogat.

Ez nem szponzorált bejegyzés - természetesen sok más megoldás is elérhető, például:

  • Digitális óceán
  • Amazon Web Services
  • Égszínkék
  • Google Cloud Platform
  • Netlify
  • ZEIT most

Nézze meg mindet, és nézze meg, melyik felel meg legjobban az Ön igényeinek.

Személy szerint Herokót találtam a leggyorsabbnak és a legkönnyebbnek a "dobozon kívül" használatba kezdeni. Az ingyenes szint az erőforrások tekintetében némileg korlátozott. Tesztelés céljából azonban magabiztosan tudom ajánlani.

Ez a példa egyszerű webhelyet fog üzemeltetni Express kiszolgáló segítségével. Itt vannak a magas szintű lépések:

  1. Beállítás Heroku, Git, npm használatával
  2. Hozzon létre egy Express.js szervert
  3. Hozzon létre statikus fájlokat
  4. Telepítsd Herokuba

Összesen körülbelül 25 percet vesz igénybe (vagy hosszabb ideig, ha több időt szeretne tölteni a statikus fájlokra).

Ez a cikk feltételezi, hogy már tudja:

  • Néhány HTML, CSS és JavaScript alap
  • Alapvető parancssori használat
  • Kezdő szintű Git a verziókezeléshez

Az összes kód megtalálható ebben az adattárban.

Felállítása

Minden projekt első lépése az összes szükséges eszköz beállítása.

Szüksége lesz a következőkre:

  • A helyi gépre telepített csomópont és npm (ennek módjáról itt olvashat)
  • Git telepítve (olvassa el ezt az útmutatót)
  • A Heroku CLI telepítve van (itt van, hogyan kell csinálni)

1. Hozzon létre egy új könyvtárat, és inicializálja a Git-tárat

A parancssorból hozzon létre egy új projektkönyvtárat, és lépjen oda.

$ mkdir lorem-ipsum-demo $ cd lorem-ipsum-demo

Most a projekt mappában van, inicializálja az új Git-tárat.

⚠️Ez a lépés azért fontos, mert a Heroku a Gitre támaszkodik, amikor kódot telepít a helyi számítógépről a felhő szervereire ⚠️

$ git init

Utolsó lépésként létrehozhat egy README.md fájlt, amelyet később szerkeszthet.

$ echo "Edit me later" > README.md

2. Jelentkezzen be a Heroku CLI-be, és hozzon létre egy új projektet

A Heroku CLI (parancssori felület) segítségével bejelentkezhet a Heroku-ba. Ehhez ingyenes Heroku-fiókkal kell rendelkeznie.

Két lehetőség van itt. Alapértelmezés szerint a Heroku lehetővé teszi a webböngészőn keresztül történő bejelentkezést. A -izászló hozzáadásával beléphet a parancssorba.

$ heroku login -i

Most létrehozhat egy új Heroku projektet. Felhívtam az enyémet lorem-ipsum-demo.

$ heroku create lorem-ipsum-demo

A projekt elnevezése:

  • A Heroku véletlenszerű nevet generál a projektedhez, ha nem adsz meg ilyet a parancsban.
  • A név része lesz annak az URL-nek, amelyet a projekt eléréséhez használhat, ezért válasszon egyet, amelyik tetszik.
  • Ez azt is jelenti, hogy ki kell választania egy egyedi projektnevet, amelyet senki más nem használt.
  • Lehetséges később átnevezni a projektet (ezért ne aggódjon túl sokat a tökéletes név megszerzése miatt).

3. Inicializáljon egy új npm projektet, és telepítse az Express.js fájlt

Ezután inicializálhat egy új npm projektet egy csomag.json fájl létrehozásával. Ehhez használja az alábbi parancsot.

⚠️Ez a lépés döntő fontosságú. A Heroku támaszkodik arra, hogy egy csomag.json fájlt ad meg, hogy tudja, hogy ez egy Node.js projekt, amikor felépíti az alkalmazást ⚠️

$ npm init -y

Ezután telepítse az Express alkalmazást. Az Express egy széles körben használt szerver keretrendszer a NodeJS számára.

$ npm install express --save

Végül készen áll a kódolás megkezdésére!

Egyszerű Express kiszolgáló írása

A következő lépés egy nevű fájl létrehozása app.js, amely helyi Express kiszolgálót futtat.

$ touch app.js

Ez a fájl lesz az alkalmazás belépési pontja, amikor elkészült. Ez azt jelenti, hogy az alkalmazás elindításához egy parancs szükséges:

$ node app.js

Először azonban be kell írnia néhány kódot a fájlba.

4. Szerkessze az app.js tartalmát

Nyissa app.jsmeg kedvenc szerkesztőjében. Írja be az alább látható kódot, és kattintson a Mentés gombra.

// create an express app const express = require("express") const app = express() // use the express-static middleware app.use(express.static("public")) // define the first route app.get("/", function (req, res) { res.send("

Hello World!

") }) // start the server listening for requests app.listen(process.env.PORT || 3000, () => console.log("Server is running..."));

A megjegyzéseknek segítenie kell a történéseket. De bontsuk le gyorsan a kódot, hogy tovább értsük:

  • The first two lines simply require the Express module and create an instance of an Express app.
  • The next line requires the use of the express.static middleware. This lets you serve static files (such as HTML, CSS and JavaScript) from the directory you specify. In this case, the files will be served from a folder called public.
  • The next line uses app.get() to define a URL route. Any URL requests to the root URL will be responded to with a simple HTML message.
  • The final part starts the server. It either looks to see which port Heroku will use, or defaults to 3000 if you are running locally.

⚠️The use of process.env.PORT || 3000 in the last line is important for deploying your app successfully ⚠️

If you save app.js and start the server with:

$ node app.js

You can visit localhost:3000 in your browser and see for yourself the server is running.

Create your static files

The next step is to create your static files. These are the HTML, CSS and JavaScript files you will serve up whenever a user visits your project.

Remember in app.js you told the express.static middleware to serve static files from the public directory.

The first step is of course to create such a directory and the files it will contain.

$ mkdir public $ cd public $ touch index.html styles.css script.js

5. Edit the HTML file

Open index.html in your preferred text editor. This will be the basic structure of the page you will serve to your visitors.

The example below creates a simple landing page for a Lorem Ipsum generator, but you can be as creative as you like here.

Lorem Ipsum generator

How many paragraphs do you want to generate?

Generate Copy!

6. Edit the CSS file

Next up is editing the CSS file styles.css. Make sure this is linked in your HTML file.

The CSS below is for the Lorem Ipsum example. But again, feel free to be as creative as you want.

h1 { font-family: 'Alegreya' ; } body { font-family: 'Source Sans Pro' ; width: 50%; margin-left: 25%; text-align: justify; line-height: 1.7; font-size: 18px; } input { font-size: 18px; text-align: center; } button { font-size: 18px; color: #fff; } #generate { background-color: #09f; } #copy { background-color: #0c6; }

7. Edit the JavaScript file

Finally, you might want to edit the JavaScript file script.js. This will let you make your page more interactive.

The code below defines two basic functions for the Lorem Ipsum generator. Yes, I used JQuery - it's quick and easy to work with.

$("#generate").click(function(){ var lorem = $("#lorem"); lorem.html(""); var quantity = $("#quantity")[0].valueAsNumber; var data = ["Lorem ipsum", "quia dolor sit", "amet", "consectetur"]; for(var i = 0; i < quantity; i++){ lorem.append("

"+data[i]+"

"); } }) $("#copy").click(function() { var range = document.createRange(); range.selectNode($("#lorem")[0]); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); document.execCommand("copy"); window.getSelection().removeAllRanges(); } )

Note that here, the data list is truncated to make it easier to show. In the actual app, it is a much longer list of full paragraphs. You can see the entire file in the repo, or look here for the original source.

Deploying your app

After writing your static code and checking it all works as expected, you can get ready to deploy to Heroku.

However, there are a couple more things to do.

8. Create a Procfile

Heroku will need a Procfile to know how to run your app.

A Procfile is a "process file" which tells Heroku which command to run in order to manage a given process. In this case, the command will tell Heroku how to start your server listening on the web.

Use the command below to create the file.

⚠️This is an important step, because without a Procfile, Heroku cannot put your server online. ⚠️

$ echo "web: node app.js" > Procfile

Notice that the Procfile has no file extension (e.g., ".txt", ".json").

Also, see how the command node app.js is the same one used locally to run your server.

9. Add and commit files to Git

Remember you initiated a Git repository when setting up. Perhaps you have been adding and committing files as you have gone.

Before you deploy to Heroku, make sure to add all the relevant files and commit them.

$ git add . $ git commit -m "ready to deploy"

The final step is to push to your Heroku master branch.

$ git push heroku master

You should see the command line print out a load of information as Heroku builds and deploys your app.

The line to look for is: Verifying deploy... done.

This shows that your build was successful.

Now you can open the browser and visit your-project-name.herokuapp.com. Your app will be hosted on the web for all to visit!

Quick recap

Below are the steps to follow to deploy a simple Express app to Heroku:

  1. Create a new directory and initialise a Git repository
  2. Login to the Heroku CLI and create a new project
  3. Initialise a new npm project and install Express.js
  4. Edit the contents of app.js
  5. Edit the static HTML, CSS and JavaScript files
  6. Create a Procfile
  7. Add and commit to Git, then push to your Heroku master branch

Things to check if your app is not working

Sometimes, despite best intentions, tutorials on the Internet don't work exactly as you expected.

The steps below should help debug some common errors you might encounter:

  • Did you initialise a Git repo in your project folder? Check if you ran git init earlier. Heroku relies on Git to deploy code from your local machine.
  • Did you create a package.json file? Check if you ran npm init -y earlier. Heroku requires a package.json file to recognise this is a Node.js project.
  • Is the server running? Make sure your Procfile uses the correct file name to start the server. Check you have web: node app.js and not web: node index.js.
  • Does Heroku know which port to listen on? Check you used app.listen(process.env.PORT || 3000) in your app.js file.
  • Do your static files have any errors in them? Check them by running locally and seeing if there are any bugs.

Thanks for reading - if you made it this far, you might want to checkout the finished version of the demo project.