From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- files/pt-pt/learn/no-servidor/django/index.html | 68 --- .../index.html | 406 ---------------- .../learn/no-servidor/express_nodejs/index.html | 76 --- .../express_nodejs/introduction/index.html | 539 --------------------- files/pt-pt/learn/no-servidor/index.html | 57 --- .../servidor_node_sem_framework/index.html | 94 ---- 6 files changed, 1240 deletions(-) delete mode 100644 files/pt-pt/learn/no-servidor/django/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/index.html delete mode 100644 files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html delete mode 100644 files/pt-pt/learn/no-servidor/index.html delete mode 100644 files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html (limited to 'files/pt-pt/learn/no-servidor') diff --git a/files/pt-pt/learn/no-servidor/django/index.html b/files/pt-pt/learn/no-servidor/django/index.html deleted file mode 100644 index 295b1e80b4..0000000000 --- a/files/pt-pt/learn/no-servidor/django/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Framework da Web Django (Python) -slug: Learn/No-servidor/Django -tags: - - Aprender - - CodingScripting - - Introdução - - Principiante - - Programação no lado do servidor - - Python - - django -translation_of: Learn/Server-side/Django ---- -
{{LearnSidebar}}
- -

Django é uma framework da web do lado do servidor extremamente popular e cheia de recursos, escrita em Python. O módulo mostra-lhe porque Django é uma das frameworks mais populares de servidor da web, como configurar um ambiente de desenvolvimento, e como começar a utilizá-lo para criar as suas próprias aplicações da web.

- -

Pré-requisitos

- -

Before starting this module you don't need to have any knowledge of Django. Ideally, you would need to understand what server-side web programming and web frameworks are by reading the topics in our Server-side website programming first steps module.

- -

A general knowledge of programming concepts and Python is recommended, but is not essential to understanding the core concepts.

- -
-

Nota: Python is one of the easiest programming languages for novices to read and understand. That said, if you want to understand this module better, there are numerous free books and tutorials available on the Internet to help you out. (new programmers might want to check out the Python for Non Programmers page on the python.org wiki).

-
- -

Guias

- -
-
Django introduction
-
In this first Django article we answer the question "What is Django?" and give you an overview of what makes this web framework special. We'll outline the main features, including some advanced functionality that we won't have time to cover in detail in this module. We'll also show you some of the main building blocks of a Django application, to give you an idea of what it can do before you set it up and start playing.
-
Setting up a Django development environment
-
Now that you know what Django is for, we'll show you how to setup and test a Django development environment on Windows, Linux (Ubuntu), and Mac OS X — whatever common operating system you are using, this article should give you what you need to be able to start developing Django apps.
-
Django Tutorial: The Local Library website
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" — an example website we'll be working through and evolving in subsequent articles.
-
Django Tutorial Part 2: Creating a skeleton website
-
This article shows how you can create a "skeleton" website project as a basis, which you can then go on to populate with site-specific settings, urls, models, views, and templates.
-
Django Tutorial Part 3: Using models
-
This article shows how to define models for the LocalLibrary website — models represent the data structures we want to store our app's data in, and also allow Django to store data in a database for us (and modify it later on). It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.
-
Django Tutorial Part 4: Django admin site
-
Now that we've created models for the LocalLibrary website, we'll use the Django Admin site to add some "real" book data. First we'll show you how to register the models with the admin site, then we'll show you how to login and create some data. At the end we show some ways in which you can further improve the presentation of the admin site.
-
Django Tutorial Part 5: Creating our home page
-
We're now ready to add the code to display our first full page — a home page for the LocalLibrary that shows how many records we have of each model type and provides sidebar navigation links to our other pages. Along the way we'll gain practical experience in writing basic URL maps and views, getting records from the database, and using templates.
-
Django Tutorial Part 6: Generic list and detail views
-
This tutorial extends our LocalLibrary website, adding list and detail pages for books and authors. Here we'll learn about generic class-based views, and show how they can reduce the amount of code you have to write for common use cases. We'll also go into URL handling in greater detail, showing how to perform basic pattern matching.
-
Django Tutorial Part 7: Sessions framework
-
This tutorial extends our LocalLibrary website, adding a session-based visit-counter to the home page. This is a relatively simple example, but it does show how you can use the session framework to provide persistent behaviour for anonymous users in your own sites.
-
Django Tutorial Part 8: User authentication and permissions
-
In this tutorial we'll show you how to allow users to login to your site with their own accounts, and how to control what they can do and see based on whether or not they are logged in and their permissions. As part of this demonstration we'll extend the LocalLibrary website, adding login and logout pages, and user- and staff-specific pages for viewing books that have been borrowed.
-
Django Tutorial Part 9: Working with forms
-
In this tutorial we'll show you how to work with HTML Forms in Django, and in particular the easiest way to write forms to create, update, and delete model instances. As part of this demonstration we'll extend the LocalLibrary website so that librarians can renew books, and create, update, and delete authors using our own forms (rather than using the admin application).
-
Django Tutorial Part 10: Testing a Django web application
-
As websites grow they become harder to test manually — not only is there more to test, but, as the interactions between components become more complex, a small change in one area can require many additional tests to verify its impact on other areas. One way to mitigate these problems is to write automated tests, which can easily and reliably be run every time you make a change. This tutorial shows how to automate unit testing of your website using Django's test framework.
-
Django Tutorial Part 11: Deploying Django to production
-
Now you've created (and tested) an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
Django web application security
-
Protecting user data is an essential part of any website design. We previously explained some of the more common security threats in the article Web security — this article provides a practical demonstration of how Django's in-built protections handle such threats.
-
- -

Avaliações

- -

The following assessment will test your understanding of how to create a website using Django, as described in the guides listed above.

- -
-
DIY Django mini blog
-
In this assessment you'll use some of the knowledge you've learned from this module to create your own blog.
-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html deleted file mode 100644 index 242d0be946..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/configurar_um_meio_de_desenvolvimento_node/index.html +++ /dev/null @@ -1,406 +0,0 @@ ---- -title: Configurar um meio de desenvolvimento Node -slug: Learn/No-servidor/Express_Nodejs/Configurar_um_meio_de_desenvolvimento_Node -tags: - - Ambiente de desenvolvimento - - Aprender - - CodingScripting - - Express - - Introdução - - Node - - Nodo - - Principiante - - lado do servidor - - nodejs - - npm -translation_of: Learn/Server-side/Express_Nodejs/development_environment ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}
- -

Agora que sabe para que serve o Express, nós iremos mostrar-lhe como configurar e testar um ambiente de desenvolvimento Node/Express no Linux, (Ubuntu), macOS e Windows. Qualquer que seja o sistema operativo comum que esteja a utilizar, este artigo deverá fornecer-lhe o que precisa para começar a desenvolver aplicações Express.

- - - - - - - - - - - - -
Pré-requisitos:Know how to open a terminal / command line. Know how to install software packages on your development computer's operating system.
Objetivo:To set up a development environment for Express (X.XX) on your computer.
- -

Resumo do ambiente de desenvolvimento Express

- -

Node and Express make it very easy to set up your computer in order to start developing web applications. This section provides an overview of what tools are needed, explains some of the simplest methods for installing Node (and Express) on Ubuntu, macOS, and Windows, and shows how you can test your installation.

- -

O que é o ambiente de desenvolvimento Express?

- -

The Express development environment includes an installation of Nodejs, the NPM package manager, and (optionally) the Express Application Generator on your local computer.

- -

Node and the NPM package manager are installed together from prepared binary packages, installers, operating system package managers or from source (as shown in the following sections). Express is then installed by NPM as a dependency of your individual Express web applications (along with other libraries like template engines, database drivers, authentication middleware, middleware to serve static files, etc.)

- -

NPM can also be used to (globally) install the Express Application Generator, a handy tool for creating skeleton Express web apps that follow the MVC pattern. The application generator is optional because you don't need to use this tool to create apps that use Express, or construct Express apps that have the same architectural layout or dependencies. We'll be using it though, because it makes getting started a lot easier, and promotes a modular application structure.

- -
-

Nota: Unlike for some other web frameworks, the development environment does not include a separate development web server. In Node/Express a web application creates and runs its own web server!

-
- -

There are other peripheral tools that are part of a typical development environment, including text editors or IDEs for editing code, and source control management tools like Git for safely managing different versions of your code. We are assuming that you've already got these sorts of tools installed (in particular a text editor).

- -

Quais são os sistemas operativos suportados?

- -

Node can be run on Windows, macOS, many "flavours" of Linux, Docker, etc. (there is a full list on the nodejs Downloads page). Almost any personal computer should have the necessary performance to run Node during development. Express is run in a Node environment, and hence can run on any platform that runs Node.

- -

In this article we provide setup instructions for Windows, macOS, and Ubuntu Linux.

- -

Que versão de Node/Express deverei utilizar?

- -

There are many releases of Node — newer releases contain bug fixes, support for more recent versions of ECMAScript (JavaScript) standards, and improvements to the Node APIs. 

- -

Generally you should use the most recent LTS (long-term supported) release as this will be more stable than the "current" release while still having relatively recent features (and is still being actively maintained). You should use the Current release if you need a feature that is not present in the LTS version.

- -

For Express you should always use the latest version.

- -

E as bases de dados e outras dependências?

- -

Other dependencies, such as database drivers, template engines, authentication engines, etc. are part of the application, and are imported into the application environment using the NPM package manager.  We'll discuss them in later app-specific articles.

- -

Instalação de Node

- -

In order to use Express you will first have to install Nodejs and the Node Package Manager (NPM) on your operating system. The following sections explain the easiest way to install the Long Term Supported (LTS) version of Nodejs on Ubuntu Linux 16.04, macOS, and Windows 10.

- -
-

Dica: The sections below show the easiest way to install Node and NPM on our target OS platforms. If you're using another OS or just want to see some of the other approaches for the current platforms then see Installing Node.js via package manager (nodejs.org).

-
- -

macOS e Windows

- -

Installing Node and NPM on Windows and macOS is straightforward because you can just use the provided installer:

- -
    -
  1. Download the required installer: -
      -
    1. Go to https://nodejs.org/en/
    2. -
    3. Select the button to download the LTS build that is "Recommended for most users".
    4. -
    -
  2. -
  3. Install Node by double-clicking on the downloaded file and following the installation prompts.
  4. -
- -

Ubuntu 16.04

- -

The easiest way to install the most recent LTS version of Node 6.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on your terminal:

- -
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
-sudo apt-get install -y nodejs
-
- -
-

Aviso: Don't install directly from the normal Ubuntu repositories because they contain very old versions of node.

-
- -
    -
- -

Testar a instalação do seu Nodejs e NPM

- -

The easiest way to test that node is installed is to run the "version" command in your terminal/command prompt and check that a version string is returned:

- -
>node -v
-v8.11.3
- -

The Nodejs package manager NPM should also have been installed, and can be tested in the same way:

- -
>npm -v
-5.8.0
- -

As a slightly more exciting test let's create a very basic "pure node" server that simply prints out "Hello World" in the browser when you visit the correct URL in your browser:

- -
    -
  1. Copy the following text into a file named hellonode.js. This uses pure Node features (nothing from Express) and some ES6 syntax: - -
    //Load HTTP module
    -const http = require("http");
    -const hostname = '127.0.0.1';
    -const port = 3000;
    -
    -//Create HTTP server and listen on port 3000 for requests
    -const server = http.createServer((req, res) => {
    -
    -  //Set the response HTTP header with HTTP status and Content type
    -  res.statusCode = 200;
    -  res.setHeader('Content-Type', 'text/plain');
    -  res.end('Hello World\n');
    -});
    -
    -//listen for request on port 3000, and as a callback function have the port listened on logged
    -server.listen(port, hostname, () => {
    -  console.log(`Server running at http://${hostname}:${port}/`);
    -});
    -
    -
    - -

    The code imports the "http" module and uses it to create a server (createServer()) that listens for HTTP requests on port 3000. The script then prints a message to the console about what browser URL you can use to test the server. The createServer() function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".

    - -
    -

    Nota:  Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!

    -
    -
  2. -
  3. Start the server by navigating into the same directory as your hellonode.js file in your command prompt, and calling node along with the script name, like so: -
    >node hellonode.js
    -Server running at http://127.0.0.1:3000/
    -
    -
  4. -
  5. Navigate to the URL http://127.0.0.1:3000 . If everything is working, the browser should simply display the string "Hello World".
  6. -
- -

Utilização de NPM

- -

Next to Node itself, NPM is the most important tool for working with Node applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. 

- -
-

Nota: From Node's perspective, Express is just another package that you need to install using NPM and then require in your own code.

-
- -

You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named package.json. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of Node it can work with, etc. The package.json file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).

- -

Adicionar dependências

- -

The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.

- -
-

Nota: Here we show the instructions to fetch and install the Express package. Later on we'll show how this package, and others, are already specified for us using the Express Application Generator. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.

-
- -
    -
  1. First create a directory for your new application and navigate into it: -
    mkdir myapp
    -cd myapp
    -
  2. -
  3. Use the npm init command to create a package.json file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults: -
    npm init
    - -

    If you display the package.json file (cat package.json), you will see the defaults that you accepted, ending with the license.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC"
    -}
    -
    -
  4. -
  5. Now install Express in the myapp directory and save it in the dependencies list of your package.json file
  6. -
  7. -
    npm install express --save
    - -

    The dependencies section of your package.json will now appear at the end of the package.json file and will include Express.

    - -
    {
    -  "name": "myapp",
    -  "version": "1.0.0",
    -  "description": "",
    -  "main": "index.js",
    -  "scripts": {
    -    "test": "echo \"Error: no test specified\" && exit 1"
    -  },
    -  "author": "",
    -  "license": "ISC",
    -  "dependencies": {
    -    "express": "^4.16.2"
    -  }
    -}
    -
    -
  8. -
  9. To use the library you call the require() function as shown below. -
    const express = require('express')
    -const app = express();
    -
    -app.get('/', (req, res) => {
    -  res.send('Hello World!')
    -});
    -
    -app.listen(8000, () => {
    -  console.log('Example app listening on port 8000!')
    -});
    -
    - -

    This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (app) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The app.get() function only responds to HTTP GET requests with the specified URL path ('/'), in this case by calling a function to send our Hello World! message. 
    -
    - Create a file named index.js in the root of the "myapp" application directory and give it the contents shown above.

    -
  10. -
  11. You can start the server by calling node with the script in your command prompt: -
    >node index.js
    -Example app listening on port 8000
    -
    -
  12. -
  13. Navigate to the URL (http://127.0.0.1:8000/). If everything is working, the browser should simply display the string "Hello World!".
  14. -
- -

Dependências de desenvolvimento

- -

If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool eslint you would call NPM as shown:

- -
npm install eslint --save-dev
- -

The following entry would then be added to your application's package.json:

- -
  "devDependencies": {
-    "eslint": "^4.12.1"
-  }
-
- -
-

Nota: "Linters" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.

-
- -

Execução de tarefas

- -

In addition to defining and fetching dependencies you can also define named scripts in your package.json files and call NPM to execute them with the run-script command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).

- -
-

Nota: Task runners like Gulp and Grunt can also be used to run tests and other external tools.

-
- -

For example, to define a script to run the eslint development dependency that we specified in the previous section we might add the following script block to our package.json file (assuming that our application source is in a folder /src/js):

- -
"scripts": {
-  ...
-  "lint": "eslint src/js"
-  ...
-}
-
- -

To explain a little further, eslint src/js is a command that we could enter in our terminal/command line to run eslint on JavaScript files contained in the src/js directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — lint.

- -

We would then be able to run eslint using NPM by calling:

- -
npm run-script lint
-# OR (using the alias)
-npm run lint
-
- -

This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.

- -

Instalar o Gerador de Aplicação Express

- -

The Express Application Generator tool generates an Express application "skeleton". Install the generator using NPM as shown (the -g flag installs the tool globally so that you can call it from anywhere):

- -
npm install express-generator -g
- -

To create an Express app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:

- -
express helloworld
- -
-

Nota: You can also specify the template library to use and a number of other settings. Use the help command to see all the options:

- -
express --help
-
- -

 

-
- -

NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.

- -
-

The new app will have a package.json file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:

- -
{
-  "name": "helloworld",
-  "version": "0.0.0",
-  "private": true,
-  "scripts": {
-    "start": "node ./bin/www"
-  },
-  "dependencies": {
-    "body-parser": "~1.18.2",
-    "cookie-parser": "~1.4.3",
-    "debug": "~2.6.9",
-    "express": "~4.15.5",
-    "jade": "~1.11.0",
-    "morgan": "~1.9.0",
-    "serve-favicon": "~2.4.5"
-  }
-}
- -

 

-
- -

Install all the dependencies for the helloworld app using NPM as shown:

- -
cd helloworld
-npm install
-
- -

Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:

- -
# Run the helloworld on Windows
-SET DEBUG=helloworld:* & npm start
-
-# Run helloworld on Linux/macOS
-DEBUG=helloworld:* npm start
-
- -

The DEBUG command creates useful logging, resulting in an output like that shown below.

- -
>SET DEBUG=helloworld:* & npm start
-
-> helloworld@0.0.0 start D:\Github\expresstests\helloworld
-> node ./bin/www
-
-  helloworld:server Listening on port 3000 +0ms
- -

Open a browser and navigate to http://127.0.0.1:3000/ to see the default Express welcome page.

- -

Express - Generated App Default Screen

- -

We'll talk more about the generated app when we get to the article on generating a skeleton application.

- - - -

Resumo

- -

You now have a Node development environment up and running on your computer that can be used for creating Express web applications. You've also seen how NPM can be used to import Express into an application, and also how you can create applications using the Express Application Generator tool and then run them.

- -

In the next article we start working through a tutorial to build a complete web application using this environment and associated tools.

- -

Consulte também

- - - -

{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}

- -

 

- -

Neste módulop

- - - -

 

diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/index.html deleted file mode 100644 index 1c7e7413ec..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/index.html +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Framework da Web Express (Node.js/JavaScript) -slug: Learn/No-servidor/Express_Nodejs -tags: - - Aprender - - CodingScripting - - Express - - Express.js - - Introdução - - JavaScript - - Node - - Nodo - - Principiante - - Programação no lado do servidor - - node.js -translation_of: Learn/Server-side/Express_Nodejs ---- -
{{LearnSidebar}}
- -

Express é uma das frameworks mais populares, escrita em JavaScript e hospedada dentro do próprio ambiente de execução node.js. Este módulo explica alguns dos benefícios chave desta framework, como configurar o seu ambiente de desenvolvimento e como realizar tarefas comuns de desenvolvimento da web e tarefas de implementação.

- -

Pré-requisitos

- -

Antes de iniciar este módulo, você precisará entender o que são os programas da web e do lado do servidor, idealmente lendo os tópicos no nosso módulo Os primeiros passos de programação do sites da Web no lado do servidor. Um conhecimento geral de conceitos de programação e JavaScript é altamente recomendado, mas não essencial para compreender os conceitos fundamentais.

- -
-

Nota: This website has many useful resources for learning JavaScript in the context of client-side development: JavaScriptJavaScript Guide, JavaScript BasicsJavaScript (learning). The core JavaScript language and concepts are the same for server-side development on Node.js and this material will be relevant. Node.js offers additional APIs for supporting functionality that is useful in browserless environments, e.g. to create HTTP servers and access the file system, but does not support JavaScript APIs for working with the browser and DOM.

- -

This guide will provide some information about working with Node.js and Express, and there are numerous other excellent resources on the Internet and in books — some of these linked from How do I get started with Node.js (StackOverflow) and What are the best resources for learning Node.js? (Quora).

-
- -

Guias

- -
-
Introdução a Express/Node
-
In this first Express article we answer the questions "What is Node?" and "What is Express?" and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).
-
Configurar um ambiente de desenvolvimento Node (Express)
-
Now that you know what Express is for, we'll show you how to set up and test a Node/Express development environment on Windows, Linux (Ubuntu), and Mac OS X. Whatever common operating system you are using, this article should give you what you need to be able to start developing Express apps.
-
Tutorial de Express: O Website - Biblioteca Local
-
The first article in our practical tutorial series explains what you'll learn, and provides an overview of the "local library" example website we'll be working through and evolving in subsequent articles.
-
Tutorial de Express Parte 2: Criar um esqueleto de um website
-
This article shows how you can create a "skeleton" website project, which you can then go on to populate with site-specific routes, templates/views, and databases.
-
Tutorial de Express Parte 3: Usar uma Base de Dados (com Mongoose)
-
This article briefly introduces databases for Node/Express. It then goes on to show how we can use Mongoose to provide database access for the LocalLibrary website. It explains how object schema and models are declared, the main field types, and basic validation. It also briefly shows a few of the main ways you can access model data.
-
Tutorial de Express Parte 4: Rotas e controladores
-
In this tutorial we'll set up routes (URL handling code) with "dummy" handler functions for all the resource endpoints that we'll eventually need in the LocalLibrary website. On completion, we'll have a modular structure for our route handling code, that we can extend with real handler functions in the following articles. We'll also have a really good understanding of how to create modular routes using Express.
-
Tutorial de Express Parte 5: Exibir dados da biblioteca
-
We're now ready to add the pages that display the LocalLibrary website books and other data. The pages will include a home page that shows how many records we have of each model type, and list and detail pages for all of our models. Along the way we'll gain practical experience in getting records from the database, and using templates.
-
Tutorial de Express Parte 6: Trabalhar com formulários
-
In this tutorial we'll show you how to work with HTML Forms in Express, using Pug, and in particular how to write forms to create, update, and delete documents from the database.
-
Tutorial de Express Parte 7: Enviar para produção
-
Now you've created an awesome LocalLibrary website, you're going to want to install it on a public web server so that it can be accessed by library staff and members over the Internet. This article provides an overview of how you might go about finding a host to deploy your website, and what you need to do in order to get your site ready for production.
-
- -

Consulte também

- -
-
Installing LocalLibrary on PWS/Cloud Foundry
-
This article provides a practical demonstration of how to install LocalLibrary on the Pivotal Web Services PaaS cloud — this is a full-featured, open source alternative to Heroku, the PaaS cloud service used in Part 7 of the tutorial, listed above. PWS/Cloud Foundry is definitely worth checking out if you are looking for an alternative to Heroku (or another PaaS cloud service), or simply feel like trying something different.
-
- -

Adicionar mais tutoriais

- -
-

That's the end of the tutorial articles (for now). If you would like to extend it, other interesting topics to cover are:

- - - -

And of course it would be excellent to have an assessment task!

-
diff --git a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html b/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html deleted file mode 100644 index c39acc6f1d..0000000000 --- a/files/pt-pt/learn/no-servidor/express_nodejs/introduction/index.html +++ /dev/null @@ -1,539 +0,0 @@ ---- -title: Introdução a Express/Node -slug: Learn/No-servidor/Express_Nodejs/Introduction -tags: - - Aprender - - CodingScripting - - Express - - Nodo - - Principiante - - lado do servidor - - nodejs -translation_of: Learn/Server-side/Express_Nodejs/Introduction ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/No-servidor/Express_Nodejs", "Learn/Server-side/Express_Nodejs")}}
- -

In this first Express article we answer the questions "What is Node?" (answer: a library) and "What is Express?", and give you an overview of what makes the Express web framework special. We'll outline the main features, and show you some of the main building blocks of an Express application (although at this point you won't yet have a development environment in which to test it).

- - - - - - - - - - - - -
Pré-requisitos:Basic computer literacy. A general understanding of server-side website programming, and in particular the mechanics of client-server interactions in websites.
Objetivo:To gain familiarity with what Express is and how it fits in with Node, what functionality it provides, and the main building blocks of an Express application.
- -

Introdução a Node

- -

Node (or more formally Node.js) is an open-source, cross-platform, runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. The runtime is intended for use outside of a browser context (i.e. running directly on a computer or server OS). As such, the environment omits browser-specific JavaScript APIs and adds support for more traditional OS APIs including HTTP and file system libraries.

- -

From a web server development perspective Node has a number of benefits:

- - - -

You can use Node.js to create a simple web server using the Node HTTP package.

- -

Hello Node.js

- -

The following example creates a web server that listens for any kind of HTTP request on the URL http://127.0.0.1:8000/ — when a request is received, the script will respond with the string: "Hello World". If you have already installed node, you can follow these steps to try out the example:

- -
    -
  1. Open Terminal (on Windows, open the command line utility)
  2. -
  3. Create the folder where you want to save the program, for example, "test-node" and then enter it by entering the following command into your terminal:
  4. -
- -
cd test-node
- -
    -
  1. Using your favorite text editor, create a file called "hello.js" and paste the following code into it:
  2. -
- -
// Load HTTP module
-var http = require("http");
-
-// Create HTTP server and listen on port 8000 for requests
-http.createServer(function(request, response) {
-
-   // Set the response HTTP header with HTTP status and Content type
-   response.writeHead(200, {'Content-Type': 'text/plain'});
-
-   // Send the response body "Hello World"
-   response.end('Hello World\n');
-}).listen(8000);
-
-// Print URL for accessing server
-console.log('Server running at http://127.0.0.1:8000/');
- -
    -
  1. Save the file in the folder you created above.
  2. -
  3. Go back to the terminal and type the following command:
  4. -
- -
node "hello.js"
- -

Finally, navigate to "http://localhost:8000" in your web browser; you should see the text "Hello World" in the upper left of an otherwise empty web page.

- -

Estruturas da Web (Frameworks)

- -

Other common web-development tasks are not directly supported by Node itself. If you want to add specific handling for different HTTP verbs (e.g. GET, POST, DELETE, etc.), separately handle requests at different URL paths ("routes"), serve static files, or use templates to dynamically create the response, then you will need to write the code yourself, or you can avoid reinventing the wheel and use a web framework!

- -

Introdução a Express

- -

Express is the most popular Node web framework, and is the underlying library for a number of other popular Node web frameworks. It provides mechanisms to:

- - - -

While Express itself is fairly minimalist, developers have created compatible middleware packages to address almost any web development problem. There are libraries to work with cookies, sessions, user logins, URL parameters, POST data, security headers, and many more. You can find a list of middleware packages maintained by the Express team at Express Middleware (along with a list of some popular 3rd party packages).

- -
-

Nota: This flexibility is a double edged sword. There are middleware packages to address almost any problem or requirement, but working out the right packages to use can sometimes be a challenge. There is also no "right way" to structure an application, and many examples you might find on the Internet are not optimal, or only show a small part of what you need to do in order to develop a web application.

-
- -

De onde veio o Node e o Express?

- -

Node was initially released, for Linux only, in 2009. The NPM package manager was released in 2010, and native Windows support was added in 2012. The current LTS release is Node v8.11.2 while the latest release is Node 10.1.0. This is a tiny snapshot of a rich history; delve into Wikipedia if you want to know more.

- -

Express was initially released in November 2010 and is currently on version 4.16 of the API. You can check out the changelog for information about changes in the current release, and GitHub for more detailed historical release notes.

- -

Quão populares são o Node e Express?

- -

The popularity of a web framework is important because it is an indicator of whether it will continue to be maintained, and what resources are likely to be available in terms of documentation, add-on libraries, and technical support.

- -

There isn't any readily-available and definitive measurement of the popularity of server-side frameworks (although sites like Hot Frameworks attempt to assess popularity using mechanisms like counting the number of GitHub projects and StackOverflow questions for each platform). A better question is whether Node and Express are "popular enough" to avoid the problems of unpopular platforms. Are they continuing to evolve? Can you get help if you need it? Is there an opportunity for you to get paid work if you learn Express?

- -

Based on the number of high profile companies that use Express, the number of people contributing to the codebase, and the number of people providing both free and paid for support, then yes, Express is a popular framework!

- -

Express é opinativo?

- -

Web frameworks often refer to themselves as "opinionated" or "unopinionated".

- -

Opinionated frameworks are those with opinions about the "right way" to handle any particular task. They often support rapid development in a particular domain (solving problems of a particular type) because the right way to do anything is usually well-understood and well-documented. However they can be less flexible at solving problems outside their main domain, and tend to offer fewer choices for what components and approaches they can use.

- -

Unopinionated frameworks, by contrast, have far fewer restrictions on the best way to glue components together to achieve a goal, or even what components should be used. They make it easier for developers to use the most suitable tools to complete a particular task, albeit at the cost that you need to find those components yourself.
-
- Express is unopinionated. You can insert almost any compatible middleware you like into the request handling chain, in almost any order you like. You can structure the app in one file or multiple files, and using any directory structure. You may sometimes feel that you have too many choices!

- -

Como é que o código de Express se parece?

- -

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

- -

Express provides methods to specify what function is called for a particular HTTP verb (GET, POST, SET, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting POST/GET parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).

- -

The following sections explain some of the common things you'll see when working with Express and Node code.

- -

Helloworld Express

- -

First lets consider the standard Express Hello World example (we discuss each part of this below, and in the following sections).

- -
-

Dica: If you have Node and Express already installed (or if you install them as shown in the next article), you can save this code in a text file called app.js and run it in a bash command prompt by calling:   

- -

./node ./app.js

-
- -
var express = require('express');
-var app = express();
-
-app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
-app.listen(3000, function() {
-  console.log('Example app listening on port 3000!');
-});
-
- -

The first two lines require() (import) the express module and create an Express application. This object, which is traditionally named app, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying application settings that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)

- -

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and simply calls send() on the response to return the string "Hello World!"

- -

The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to localhost:3000 in your browser to see the example response returned.

- -

Importação e criação de módulos

- -

A module is a JavaScript library/file that you can import into other code using Node's require() function. Express itself is a module, as are the middleware and database libraries that we use in our Express applications.

- -

The code below shows how we import a module by name, using the Express framework as an example. First we invoke the require() function, specifying the name of the module as a string ('express'), and calling the returned object to create an Express application. We can then access the properties and functions of the application object.

- -
var express = require('express');
-var app = express();
-
- -

You can also create your own modules that can be imported in the same way.

- -
-

Dica: You will want to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.

-
- -

To make objects available outside of a module you just need to assign them to the exports object. For example, the square.js module below is a file that exports area() and perimeter() methods:

- -
exports.area = function(width) { return width * width; };
-exports.perimeter = function(width) { return 4 * width; };
-
- -

We can import this module using require(), and then call the exported method(s) as shown:

- -
var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension
-console.log('The area of a square with a width of 4 is ' + square.area(4));
- -
-

Nota: You can also specify an absolute path to the module (or a name, as we did initially).

-
- -

If you want to export a complete object in one assignment instead of building it one property at a time, assign it to module.exports as shown below (you can also do this to make the root of the exports object a constructor or other function):

- -
module.exports = {
-  area: function(width) {
-    return width * width;
-  },
-
-  perimeter: function(width) {
-    return 4 * width;
-  }
-};
-
- -

For a lot more information about modules see Modules (Node API docs).

- -

Utilizar APIs assíncronas

- -

JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).

- -
console.log('First');
-console.log('Second');
-
- -

By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though setTimeout() method is called first, and returns immediately, the operation doesn't complete for several seconds.

- -
setTimeout(function() {
-   console.log('First');
-   }, 3000);
-console.log('Second');
-
- -

Using non-blocking asynchronous APIs is even more important on Node than in the browser, because Node is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.

- -

There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.

- -
-

Dica: Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see http://callbackhell.com/), using a module like async, or even moving to ES6 features like Promises.

-
- -
-

Nota: A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your callback functions is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: The Node.js Way - Understanding Error-First Callbacks (fredkschott.com).

-
- -

Criação de manipuladores de rota

- -

In our Hello World Express example (see above), we defined a (callback) route handler function for HTTP GET requests to the site root ('/').

- -
app.get('/', function(req, res) {
-  res.send('Hello World!');
-});
-
- -

The callback function takes a request and a response object as arguments. In this case the method simply calls send() on the response to return the string "Hello World!" There are a number of other response methods for ending the request/response cycle, for example you could call res.json() to send a JSON response or res.sendFile() to send a file.

- -
-

Dica de JavaScript: You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.

-
- -

The Express application object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: post(), put(), delete(), options(), trace(), copy(), lock(), mkcol(), move(), purge(), propfind(), proppatch(), unlock(), report(), mkactivity(), checkout(), merge(), m-search(), notify(), subscribe(), unsubscribe(), patch(), search(), and connect().

- -

There is a special routing method, app.all(), which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to /secret irrespective of the HTTP verb used (provided it is supported by the http module).

- -
app.all('/secret', function(req, res, next) {
-  console.log('Accessing the secret section ...');
-  next(); // pass control to the next handler
-});
- -

Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).

- -

Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of /wiki/). In Express this is achieved by using the express.Router object. For example, we can create our wiki route in a module named wiki.js, and then export the Router object, as shown below:

- -
// wiki.js - Wiki route module
-
-var express = require('express');
-var router = express.Router();
-
-// Home page route
-router.get('/', function(req, res) {
-  res.send('Wiki home page');
-});
-
-// About page route
-router.get('/about', function(req, res) {
-  res.send('About this wiki');
-});
-
-module.exports = router;
-
- -
-

Note: Adding routes to the Router object is just like adding routes to the app object (as shown previously).

-
- -

To use the router in our main app file we would then require() the route module (wiki.js), then call use() on the Express application to add the Router to the middleware handling path. The two routes will then be accessible from /wiki/ and /wiki/about/.

- -
var wiki = require('./wiki.js');
-// ...
-app.use('/wiki', wiki);
- -

We'll show you a lot more about working with routes, and in particular about using the Router, later on in the linked section Routes and controllers .

- -

Utilização de middleware

- -

Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions typically perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.

- -
-

Nota: The middleware can perform any operation, execute any code, make changes to the request and response object, and it can also end the request-response cycle. If it does not end the cycle then it must call next() to pass control to the next middleware function (or the request will be left hanging).

-
- -

Most apps will use third-party middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request POST and JSON data, logging, etc. You can find a list of middleware packages maintained by the Express team (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.

- -

To use third party middleware you first need to install it into your app using NPM. For example, to install the morgan HTTP request logger middleware, you'd do this:

- -
$ npm install morgan
-
- -

You could then call use() on the Express application object to add the middleware to the stack:

- -
var express = require('express');
-var logger = require('morgan');
-var app = express();
-app.use(logger('dev'));
-...
- -
-

Nota: Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.

-
- -

You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The only difference between a middleware function and a route handler callback is that middleware functions have a third argument next, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the next function that must be called).

- -

You can add a middleware function to the processing chain with either app.use() or app.add(), depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (GET, POST, etc). You specify routes the same in both cases, though the route is optional when calling app.use().

- -

The example below shows how you can add the middleware function using both methods, and with/without a route.

- -
var express = require('express');
-var app = express();
-
-// An example middleware function
-var a_middleware_function = function(req, res, next) {
-  // ... perform some operations
-  next(); // Call next() so Express will call the next middleware function in the chain.
-}
-
-// Function added with use() for all routes and verbs
-app.use(a_middleware_function);
-
-// Function added with use() for a specific route
-app.use('/someroute', a_middleware_function);
-
-// A middleware function added for a specific HTTP verb and route
-app.get('/', a_middleware_function);
-
-app.listen(3000);
- -
-

Dica de JavaScript: Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.

-
- -

The Express documentation has a lot more excellent documentation about using and writing Express middleware.

- -

Servindo ficheiros estásticos

- -

You can use the express.static middleware to serve static files, including your images, CSS and JavaScript (static() is the only middleware function that is actually part of Express). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named 'public' at the same level as where you call node:

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

Any files in the public directory are served by adding their filename (relative to the base "public" directory) to the base URL. So for example:

- -
http://localhost:3000/images/dog.jpg
-http://localhost:3000/css/style.css
-http://localhost:3000/js/app.js
-http://localhost:3000/about.html
-
- -

You can call static() multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).

- -
app.use(express.static('public'));
-app.use(express.static('media'));
-
- -

You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we specify a mount path so that the files are loaded with the prefix "/media":

- -
app.use('/media', express.static('public'));
-
- -

Now, you can load the files that are in the public directory from the /media path prefix.

- -
http://localhost:3000/media/images/dog.jpg
-http://localhost:3000/media/video/cat.mp4
-http://localhost:3000/media/cry.mp3
-
- -

For more information, see Serving static files in Express.

- -

Erros de manipulação

- -

Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: (err, req, res, next). For example:

- -
app.use(function(err, req, res, next) {
-  console.error(err.stack);
-  res.status(500).send('Something broke!');
-});
-
- -

These can return any content required, but must be called after all other app.use() and routes calls so that they are the last middleware in the request handling process!

- -

Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to next() and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.

- -
-

Nota: The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable NODE_ENV to 'production'.

-
- -
-

Nota: HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the FAQ.

-
- -

For more information see Error handling (Express docs).

- -

Utilização de bases de dados

- -

Express apps can use any database mechanism supported by Node (Express itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.

- -

In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:

- -
$ npm install mongodb
-
- -

The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.

- -
//this works with older versions of  mongodb version ~ 2.2.33
-var MongoClient = require('mongodb').MongoClient;
-
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) {
-  if (err) throw err;
-
-  db.collection('mammals').find().toArray(function (err, result) {
-    if (err) throw err;
-
-    console.log(result);
-  });
-});
-
-
-//for mongodb version 3.0 and up
-let MongoClient = require('mongodb').MongoClient;
-MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){
-   if(err) throw err;
-
-   let db = client.db('animals');
-   db.collection('mammals').find().toArray(function(err, result){
-     if(err) throw err;
-     console.log(result);
-     client.close();
-   });
-}
-
- -

 

- -

 

- -

 

- -

Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.

- -

For more information see Database integration (Express docs).

- -

Renderização de dados (visualizações)

- -

Template engines (referred to as "view engines" by Express) allow you to specify the structure of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for a number of template engines, and there is a useful comparison of the more popular engines here: Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More.

- -

In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)

- -
var express = require('express');
-var app = express();
-
-// Set directory to contain the templates ('views')
-app.set('views', path.join(__dirname, 'views'));
-
-// Set view engine to use, in this case 'some_template_engine_name'
-app.set('view engine', 'some_template_engine_name');
-
- -

The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call Response.render() in a route handler function to create and send the HTML response:

- -
app.get('/', function(req, res) {
-  res.render('index', { title: 'About dogs', message: 'Dogs rock!' });
-});
- -

For more information see Using template engines with Express (Express docs).

- -

Estrutura de ficheiro

- -

Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole Express application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an MVC architecture).

- -

In a later topic we'll use the Express Application Generator, which creates a modular app skeleton that we can easily extend for creating web applications.

- - - -

Resumo

- -

Congratulations, you've completed the first step in your Express/Node journey! You should now understand Express and Node's main benefits, and roughly what the main parts of an Express app might look like (routes, middleware, error handling, and template code). You should also understand that with Express being an unopinionated framework, the way you pull these parts together and the libraries that you use are largely up to you!

- -

Of course Express is deliberately a very lightweight web application framework, so much of its benefit and potential comes from third party libraries and features. We'll look at those in more detail in the following articles. In our next article we're going to look at setting up a Node development environment, so that you can start seeing some Express code in action.

- -

Consulte também

- - - -
{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}
- -

Neste módulo

- - diff --git a/files/pt-pt/learn/no-servidor/index.html b/files/pt-pt/learn/no-servidor/index.html deleted file mode 100644 index b8cc8d35f7..0000000000 --- a/files/pt-pt/learn/no-servidor/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Programação do site da Web no lado do servidor -slug: Learn/No-servidor -tags: - - Aprender - - Código - - Iniciante - - Introdução - - Programação no servidor - - Scripting - - Servidor - - Tópico -translation_of: Learn/Server-side ---- -
{{LearnSidebar}}
- -

O tópico Sites da Web Dinâmicos - Programação no lado do servidor é uma série de módulos que mostram como criar sites da web dinâmicos; sites da web que entregam informação personalizada em resposta aos pedidos de HTTP. Os módulos proporcionam uma introdução genérica à programação no lado do servidor, bem como guias especificamente desenvolvidos para principiantes sobre como utilizar as estruturas de Django (Python) e Express (Node.js/JavaScript) para criar aplicações básicas.

- -

A maioria dos maiores sites da web utilizam algum tipo de tecnologia no lado do servidor para exibir dados diferentes, conforme o necessário. Por exemplo, imagine quantos produtos é que estão disponíveis na Amazon e imagine quantos artigos é que foram escritos no Facebook? Exibir todo este conteúdo utilizando páginas estáticas completamente diferentes seria absolutamente ineficiente, assim em vez disso, estes sites exibem modelos estáticos (criados utilizando CSS, HTML e JavaScript), e depois atualizam os dados dinamicamente, exibindo-os dentro dos modelos quando necessário, por exemplo, quando tenta ver um produto diferente na Amazon.

- -

No mundo moderno do desenvolvimento da web, aprender sobre o desenvolvimento no lado do servidor é altamente recomendado.

- -

Caminho de aprendizagem

- -

Começar com programação web no servidor é, de um modo geral, mais fácil que começar com desenvolvimento no lado do cliente, pois páginas web dinâmicas tendem a executar operações muito similares (adquirir dados e guardar na base de dados, verificar as permissões dos usuários, registrar usuários, etc.) , e são construídos utilizando frameworks, os quais tornam estas e outras operações de servidores web fáceis.

- -

Ter conhecimentos básicos de conceitos de programação (ou de uma linguagem de programação específica) é útil, mas não essencial. Da mesma forma, experiência com código do lado do cliente não é absolutamente necessária, mas um conhecimento básico irá ajuda-lo a trabalhar melhor com os desenvolvedores que criam o "front-end" do seu website.

- -

Precisará de compreender "como a web funciona". Recomendamos que comece por ler os seguintes tópicos:

- - - -

Com a compreensão básica destes conceitos, estará pronto para continuar no seu caminho pelos módulos nesta secção.

- -

Módulos

- -

This topic contains the following modules. You should start with the first module, then go on to one of the following modules, which show how to work with two very popular server-side languages using appropriate web frameworks . 

- -
-
Primeiros passos na programação web em servidores
-
This module provides server-technology-agnostic information about server-side website programming, including answers to fundamental questions about server-side programming — "what it is", "how it differs from client-side programming", and "why it is so useful" — and an overview of some of the more popular server-side web frameworks and guidance on how to select the most suitable for your site. Lastly we provide an introductory section on web server security.
-
Framework da Web Django (Python)
-
Django is an extremely popular and fully featured server-side web framework, written in Python. The module explains why Django is such a good web server framework, how to set up a development environment and how to perform common tasks with it.
-
Express Web Framework (Node.js/JavaScript)
-
Express is a popular web framework, written in JavaScript and hosted within the node.js runtime environment. The module explains some of the key benefits of this framework, how to set up your development environment and how to perform common web development and deployment tasks.
-
- -

Consulte também

- -
-
Servidor de Node sem uma framework
-
Este artigo fornece um servidor de ficheiros estático simples criado com Node.js puro, para aqueles que não desejam utilizar uma framework.
-
diff --git a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html b/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html deleted file mode 100644 index 85bd786b58..0000000000 --- a/files/pt-pt/learn/no-servidor/servidor_node_sem_framework/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Servidor de Node.js sem uma framework -slug: Learn/No-servidor/Servidor_node_sem_framework -tags: - - JavaScript - - Nodo - - Precisa de Conteúdo - - Servidor - - sem estrutura -translation_of: Learn/Server-side/Node_server_without_framework ---- -
{{LearnSidebar}}
- -

 

- -

Este artigo fornece um servidor de ficheiros estático simples com Node.js puro, sem a utilização de uma framework.

- -

NodeJS tem muitas frameworks para ajudá-lo a ter o seu servidor configurado e a funcionar.

- - - -

Estas não irão corresponder a todas as situações. Um programador pode precisar de criar o seu próprio servidor sem outras dependências.

- -

Exemplo

- -

Um servidor de ficheiros estático simples, criado com Node.js:

- -

 

- -
var http = require('http');
-var fs = require('fs');
-var path = require('path');
-
-http.createServer(function (request, response) {
-    console.log('request ', request.url);
-
-    var filePath = '.' + request.url;
-    if (filePath == './') {
-        filePath = './index.html';
-    }
-
-    var extname = String(path.extname(filePath)).toLowerCase();
-    var contentType = 'text/html';
-    var mimeTypes = {
-        '.html': 'text/html',
-        '.js': 'text/javascript',
-        '.css': 'text/css',
-        '.json': 'application/json',
-        '.png': 'image/png',
-        '.jpg': 'image/jpg',
-        '.gif': 'image/gif',
-        '.wav': 'audio/wav',
-        '.mp4': 'video/mp4',
-        '.woff': 'application/font-woff',
-        '.ttf': 'application/font-ttf',
-        '.eot': 'application/vnd.ms-fontobject',
-        '.otf': 'application/font-otf',
-        '.svg': 'application/image/svg+xml'
-    };
-
-    contentType = mimeTypes[extname] || 'application/octet-stream';
-
-    fs.readFile(filePath, function(error, content) {
-        if (error) {
-            if(error.code == 'ENOENT'){
-                fs.readFile('./404.html', function(error, content) {
-                    response.writeHead(200, { 'Content-Type': contentType });
-                    response.end(content, 'utf-8');
-                });
-            }
-            else {
-                response.writeHead(500);
-                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
-                response.end();
-            }
-        }
-        else {
-            response.writeHead(200, { 'Content-Type': contentType });
-            response.end(content, 'utf-8');
-        }
-    });
-
-}).listen(8125);
-console.log('Server running at http://127.0.0.1:8125/');
- -

 

- -

A efetuar

- -

Estenda este artigo, explicando como é que o código acima funciona. Talvez, uma versão estendida que sirva os ficheiros estáticos e lide com pedidos dinâmicos.

-- cgit v1.2.3-54-g00ecf