Desplegar un projecte web amb Express i Heroku
Contingut
Introducció
Usualment les aplicacions web funcionen sota Apache. Per ex:
Podem fer córrer aquesta aplicació sota Node.js (Express.js). Seria de la forma:
Ara bé, podem publicar (desplegar) aquesta aplicació al núvol de la forma:
Anem a veure com ho podem fer.
Què és Express.js
Express.js és un framework de Node.js per fer aplicacions web. Amb Node.js podem fer moltes coses, aplicacions de molts tipus, entre elles, aplicacions web (servir pàgines web). Quan es tracta de fer una aplicació web, és usuari utilitzar Express.js, que ha esdevingut un estàndard.
Què és Heroku
Quan creem una aplicació web amb Express podem accedir a l'aplicació, per exemple:
Com podem desplegar aquesta aplicació al núvol. Una solució és per exemple Heroku (una altra seria AWS).
Primer de tot creo un compte (Signup for free):
joanqc@gmail.com / jq.********
Tutorial inicial
Instal·lem el client CLI de Heroku:
$ sudo apt-get install snapd $ sudo snap install --classic heroku ... heroku v7.39.0 from Heroku✓ installed
Create Heroku app
$ /snap/bin/heroku create municipis_tablesorter
You can login to Heroku using the Heroku CLI (command line interface). You will need to have a free Heroku account to do this. Prèviament he creat un compte.
Setting up
1. Create a new directory and initialise a Git repository
El meu projecte:
cd /home/joan/M06_WEC_1920/UF2/ mkdir municipis_tablesorter cd municipis_tablesorter
git init echo "Edit me later" > README.md
2. Login to the Heroku CLI and create a new project
$ /snap/bin/heroku login -i $ /snap/bin/heroku create municipis_tablesorte › Warning: heroku update available from 7.39.0 to 7.39.2. Creating ⬢ municipis_tablesorte... ! ▸ Name must start with a letter, end with a letter or digit and can only ▸ contain lowercase letters, digits, and dashes. joan@joanHP:~/M06_WEC_1920/UF2/municipis_tablesorter$ /snap/bin/heroku create municipis-tablesorte › Warning: heroku update available from 7.39.0 to 7.39.2. Creating ⬢ municipis-tablesorte... done https://municipis-tablesorte.herokuapp.com/ | https://git.heroku.com/municipis-tablesorte.git
3. Initialise a new npm project and install Express.js
Next, you can initialise a new npm project by creating a package.json file. Use the command below to do this.
$ npm init -y
Next, install Express. Express is a widely used server framework for NodeJS.
$ npm install express --save
Writing a simple Express server
The next step is to create a file called app.js, which runs an Express server locally.
$ joe app.js
This file will be the entry point for the app when it is ready. That means, the one command needed to launch the app will be:
$ node app.js
Però abans de res hem d'escriure codi.
4. Edit the contents of app.js
script app.js: És un servidor web que escolta pel port 3000, i que utilitza express.static. Això significa que es podran interpretar bé els scripts que tenim a public/ (fitxers html, css, js):
// 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("<h1>Hello World!</h1>") }) // start the server listening for requests app.listen(process.env.PORT || 3000, () => console.log("Server is running..."));
Ja podem arrencar l'aplicació i visitar-la:
$ node app.js
- localhost:3000
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, 6, 7. Editem els fitxers HTML, CSS i JS
Els fitxers index.html, styles.css i script.js (codi en el tutorial) són una petita aplicació que utilitza JQuery.
tornem a comprovar que funciona el projecte:
cd .. $ node app.js
Deploying your app
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.
$ echo "web: node app.js" > Procfile
9. Add and commit files to Git
Hem de fer el commit dels fitxers del repositori, abans de pujar el nostre repositori a Heroke:
$ git add . $ git commit -m "ready to deploy"
The final step is to push to your Heroku master branch.
$ git push heroku master ... remote: -----> Compressing... remote: Done: 22.6M remote: -----> Launching... remote: Released v3 remote: https://municipis-tablesorte.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done. To https://git.heroku.com/municipis-tablesorte.git * [new branch] master -> master
estem pujant al nostre repositori remot de Heroku tot el nostre projecte. El repositori es diu heroku per defecte. Podia canviar el nom a l'hora de crear-lo (/snap/bin/heroku create --help)
Now you can open the browser and visit https://municipis-tablesorte.herokuapp.com/. Your app will be hosted on the web for all to visit!
Llista municipis: tablesorter, IDESCAT
Aquest és el nostre projecte sobre Apache (la ruta serà la que hagis configurat en el site de l'Apache):
I hem d'aconseguir fer córrer la mateixa aplicació sota Express:
Per fer-ho n'hi ha prou en posar tots els script necessaris sota la carpeta public/, amb les rutes correctes:
- public/llista_municipis_v2.html
- public/dist/*
- public/docs/css/jq.css
- public/docs/js/jquery-latest.min.js
<link href="./docs/css/jq.css" rel="stylesheet"> <!-- jQuery: required (tablesorter works with jQuery 1.2.3+) --> <script src="./docs/js/jquery-latest.min.js"></script> <!-- Pick a theme, load the plugin & initialize plugin --> <link href="./dist/css/theme.default.min.css" rel="stylesheet"> <script src="./dist/js/jquery.tablesorter.min.js"></script> <script src="./dist/js/jquery.tablesorter.widgets.min.js"></script>
Un cop tenim el projecte funcionant en local, ja el podem desplegar a heroku.com:
$ git add . $ git commit -m "ready to deploy 2" $ git push heroku master
NOTA: en el codi hem canviat la crida a la API de IDESCAT, http per https:
Desplegament d'una aplicació de React a Heroku
Comencem amb una aplicació nova de React:
npx create-react-app hello-world cd hello-world joe server.js npm install --save-dev express npm install --save-dev express-favicon npm install --save-dev path package.json -> "node server.js" $ npm start
You can now view hello-world in the browser.
- Local: http://localhost:3000
- On Your Network: http://192.168.1.61:3000
Note that the development build is not optimized. To create a production build, use npm run build.
$ npm run build $ serve -s build http://localhost:5000
Step 5: Prevent source code from being deployed. In your repository, create a file called .env :
joe .env GENERATE_SOURCEMAP=false
$ heroku login -i $ heroku create joanillo-hello-world
Then push your app build to heroku with the following git in your terminal:
yarn install -> npm install (instal·lar les dependències) git add . (inclou el git init, suposo) git commit -m "initial commit" heroku git:remote -a joanillo-hello-world git push heroku master heroku open
i em dóna el mateix error:
$ heroku logs --tail heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/"
Aquesta és una forma senzilla que ha funcionat. Provem això:
npm install -g create-react-app create-react-app my-app2 cd my-app2 git init heroku create -b https://github.com/mars/create-react-app-buildpack.git git add . git commit -m "react-create-app on Heroku" git push heroku master heroku open
i això ha funcionat
heroku create --help -b, --buildpack=buildpack buildpack url to use for this app
i ara ja funciona amb aquest buildpack:
cd my-app git init heroku create -b https://github.com/mars/create-react-app-buildpack.git git add . git commit -m "react-create-app on Heroku" git push heroku master heroku open
És l'aplicació del tic-tac-toe que he fet amb React.
Res de Express, molt més ràpid
created this community buildpack to experiment with no-configuration deployment to Heroku.
creat per Joan Quintana Compte, abril 2020