Giter Club home page Giter Club logo

learning-javascript's Introduction

References

Best Practices

Tools

Perfomance

HTTP Methods

  • POST vs PUT vs PATCH
    • Use POST para criação de novos recursos em endpoints de coleção, como api.biblioteca.com/livros.
    • Use PUT para atualização de recursos em endpoints de entidade, como api.biblioteca.com/livros/iliada.
    • Use PATCH para atualização parcial de recursos, também em endpoints de entidade.
  • Resumo
+-----------------------------+-----+------+-----+-------+--------+
|                             | GET | POST | PUT | PATCH | DELETE |
+-----------------------------+-----+------+-----+-------+--------+
| Requisição aceita body?     | Não | Sim  | Sim | Sim   | Sim    |
| Resposta aceita body?       | Sim | Sim  | Sim | Sim   | Sim    |
| Altera estado dos recursos? | Não | Sim  | Sim | Sim   | Sim    |
| É idempotente?              | Sim | Não  | Sim | Não   | Sim    |
| É cacheável?                | Sim | Não* | Não | Não   | Não    |
+-----------------------------+-----+------+-----+-------+--------+
* depende do que vier nos headers

HTTP Status Codes

Informational 1xx

  • 100 - Continue - Client should continue with request.
  • 101 - Switching Protocols - Server is switching protocols.
  • 102 - Processing - Server has received and is processing the request.
  • 103 - Processing - Server has received and is processing the request.
  • 122 - Request-uri too long - URI is longer than a maximum of 2083 characters.

Success 2xx

These codes indicate success. The body section if present is the object returned by the request. It is a MIME format object. It is in MIME format, and may only be in text/plain, text/html or one fo the formats specified as acceptable in the request.

  • 200 - Ok - The request was fulfilled.
  • 201 - Created - Following a POST command, this indicates success, but the textual part of the response line indicates the URI by which the newly created document should be known.
  • 202 - Accepted - The request has been accepted for processing, but the processing has not been completed. The request may or may not eventually be acted upon, as it may be disallowed when processing actually takes place. there is no facility for status returns from asynchronous operations such as this.
  • 203 - Partial Information - When received in the response to a GET command, this indicates that the returned metainformation is not a definitive set of the object from a server with a copy of the object, but is from a private overlaid web. This may include annotation information about the object, for example.
  • 204 - No Response - Server has received the request but there is no information to send back, and the client should stay in the same document view. This is mainly to allow input for scripts without changing the document at the same time.
  • 205 - Reset Content - Request processed, no content returned, reset document view.
  • 206 - Partial Content - partial resource return due to request header.
  • 207 - Multi-Status - XML, can contain multiple separate responses.
  • 208 - Already Reported - results previously returned.
  • 226 - Im Used - request fulfilled, reponse is instance-manipulations.

Redirection 3xx

The codes in this section indicate action to be taken (normally automatically) by the client in order to fulfill the request.

  • 301 - Moved - The data requested has been assigned a new URI, the change is permanent. (N.B. this is an optimisation, which must, pragmatically, be included in this definition. Browsers with link editing capabiliy should automatically relink to the new reference, where possible)
  • 302 - Found - The data requested actually resides under a different URL, however, the redirection may be altered on occasion (when making links to these kinds of document, the browser should default to using the Udi of the redirection document, but have the option of linking to the final document) as for "Forward".
  • 303 - Method - Like the found response, this suggests that the client go try another network address. In this case, a different method may be used too, rather than GET.
  • 304 - Not Modified - If the client has done a conditional GET and access is allowed, but the document has not been modified since the date and time specified in If-Modified-Since field, the server responds with a 304 status code and does not send the document body to the client.
  • 305 - Use Proxy - Content located elsewhere, retrieve from there.
  • 306 - Switch Proxy - Subsequent requests should use the specified proxy.
  • 307 - Temporary Redirect - Connect again to different URI as provided.
  • 308 - Permanent Redirect - Connect again to a different URI using the same method.

Client side errors 4xx

The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational.

The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

  • 400 - Bad Request - The request had bad syntax or was inherently impossible to be satisfied.
  • 401 - Unauthorized - The parameter to this message gives a specification of authorization schemes which are acceptable. The client should retry the request with a suitable Authorization header.
  • 402 - Payment Required - The parameter to this message gives a specification of charging schemes acceptable. The client may retry the request with a suitable ChargeTo header.
  • 403 - Forbidden - The request is for something forbidden. Authorization will not help.
  • 404 - Not Found - The server has not found anything matching the URI given.
  • 405 - Method Not Allowed - Request method not supported by that resource.
  • 406 - Not Acceptable - Content not acceptable according to the Accept headers.
  • 407 - Proxy Authentication Required - Client must first authenticate itself with the proxy.
  • 408 - Request Timeout - Server timed out waiting for the request.
  • 409 - Conflict - Request could not be processed because of conflict.
  • 410 - Gone - Resource is no longer available and will not be available again.
  • 411 - Length Required - Request did not specify the length of its content.
  • 412 - Precondition Failed - Server does not meet request preconditions.
  • 413 - Request Entity Too Large - Request is larger than the server is willing or able to process.
  • 414 - Request URI Too Large - URI provided was too long for the server to process.
  • 415 - Unsupported Media Type - Server does not support media type.
  • 416 - Requested Rage Not Satisfiable - Client has asked for unprovidable portion of the file.
  • 417 - Expectation Failed - Server cannot meet requirements of Expect request-header field.
  • 418 - I'm a teapot - I'm a teapot.
  • 420 - Enhance Your Calm - Twitter rate limiting.
  • 421 - Misdirected Request - Server is not able to produce a response.
  • 422 - Unprocessable Entity - Request unable to be followed due to semantic errors.
  • 423 - Locked - Resource that is being accessed is locked.
  • 424 - Failed Dependency - Request failed due to failure of a previous request.
  • 426 - Upgrade Required - Client should switch to a different protocol.
  • 428 - Precondition Required - Origin server requires the request to be conditional.
  • 429 - Too Many Requests - User has sent too many requests in a given amount of time.
  • 431 - Request Header Fields Too Large - Server is unwilling to process the request.
  • 444 - No Response - Server returns no information and closes the connection.
  • 449 - Retry With - Request should be retried after performing action.
  • 450 - Blocked By Windows Parental Controls - Windows Parental Controls blocking access to webpage.
  • 451 - Wrong Exchange Server - The server cannot reach the client's mailbox.
  • 499 - Client Closed Request - Connection closed by client while HTTP server is processing.

Server side error 5xx

This means that even though the request appeared to be valid something went wrong at the server level and it wasn’t able to return anything.

  • 500 - Internal Error - The server encountered an unexpected condition which prevented it from fulfilling the request.
  • 501 - Not Implemented - The server does not support the facility required.
  • 502 - Service temporarily overloaded - The server cannot process the request due to a high load (whether HTTP servicing or other requests). The implication is that this is a temporary condition which maybe alleviated at other times.
  • 503 - Gateway timeout - This is equivalent to Internal Error 500, but in the case of a server which is in turn accessing some other service, this indicates that the respose from the other service did not return within a time that the gateway was prepared to wait. As from the point of view of the clientand the HTTP transaction the other service is hidden within the server, this maybe treated identically to Internal error 500, but has more diagnostic value.
  • 504 - Gateway Timeout - Gateway did not receive response from upstream server.
  • 505 - Http Version Not Supported - Server does not support the HTTP protocol version.
  • 506 - Variant Also Negotiates - Content negotiation for the request results in a circular reference.
  • 507 - Insufficient Storage - Server is unable to store the representation.
  • 508 - Loop Detected - Server detected an infinite loop while processing the request.
  • 509 - Bandwidth Limit Exceeded - Bandwidth limit exceeded.
  • 510 - Not Extended - Further extensions to the request are required.
  • 511 - Network Authentication Required - Client needs to authenticate to gain network access.
  • 598 - Network Read Timeout Error - Network read timeout behind the proxy.
  • 599 - Network Connect Timeout Error - Network connect timeout behind the proxy.

Syntax

  • ARRAY -É um grupo de valores geralmente relacionados. Servem para guardarmos diferentes valores em uma única variável.
var videoGames = ['Switch', 'PS4', 'XBox'];
videoGames[0] // Switch
videoGames[2] // Xbox
  • MÉTODOS E PROPRIEDADES DE UMA ARRAY
var videoGames = ['Switch', 'PS4', 'XBox'];
videoGames.pop(); // Remove o último item e retorna ele
videoGames.push('3DS'); // Adiciona ao final da array
videoGames.length; // 3
  • FOR LOOP
    • Fazem algo repetidamente até que uma condição seja atingida.
for (var numero = 0; numero < 10; numero++) {
  console.log(numero);
}
// Retorna de 0 a 9 no console
  • O for loop possui 3 partes, início, condição e incremento

  • WHILE LOOP

var i = 0;
while (i < 10) {
  console.log(i);
  i++;
}
// Retorna de 0 a 9 no console
  • O for loop é o mais comum

  • ARRAYS E LOOPS

var videoGames = ['Switch', 'PS4', 'XBox', '3DS'];
for (var i = 0; i < videoGames.length; i++) {
  console.log(videoGames[i]);
}
  • O for loop é o mais comum

  • BREAK

    • O loop irá parar caso encontro e palavra break
var videoGames = ['Switch', 'PS4', 'XBox', '3DS'];
for (var i = 0; i < videoGames.length; i++) {
  console.log(videoGames[i]);
  if(videoGames[i] === 'PS4') {
    break;
  }
}
  • FOREACH
    • forEach é um método que executa uma função para cada item da Array. É uma forma mais simples de utilizarmos um loop com arrays (ou array-like)
var videoGames = ['Switch', 'PS4', 'XBox', '3DS'];
videoGames.forEach(function(item) {
  console.log(item);
});
// O argumento item será atribuído dinamicamente
  • Podemos passar os seguintes parâmetros item, index e array

  • NÃO SE CONFUNDA COM A SINTAXE

var numero = 0;
var maximo = 50;
for(;numero < maximo;) {
  console.log(numero);
  numero++;
}
  • HTTP
    • Hypertext Transfer Protocol é o protocolo utilizando para enviarmos/recebermos arquivos e dados na Web.
fetch('https://pokeapi.co/api/v2/pokemon/')
.then(r => r.json())
.then(pokemon => {
  console.log(pokemon);
});
  • URL E METHOD
    • Uma requisição HTTP é feita através de uma URL. O método padrão é o GET, mas existem outros como POST, UPDATE, DELETE, HEADER.
const url = 'https://jsonplaceholder.typicode.com/posts/';
const options = {
  method: 'POST',
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
  body: '"aula": "JavaScript"';
}

fetch(url, options);
.then(response => response.json())
.then(json => {
  console.log(json);
});
  • GET
    • Irá puxar as informações da URL. Não é necessário informar que o método é GET, pois este é o padrão.
const url = 'https://jsonplaceholder.typicode.com/posts/';
fetch(url, {
  method: 'GET'
})
.then(r => r.json())
.then(r => console.log(r))
  • POST
    • POST irá criar uma nova postagem, utilizando o tipo de conteúdo especificado no headers e utilizando o conteúdo do body.
const url = 'https://jsonplaceholder.typicode.com/posts/';

fetch(url, {
  method: 'POST',
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
  body: '{"titulo": "JavaScript"}'
})
.then(r => r.json())
.then(r => console.log(r))
  • PUT
    • PUT irá atualizar o conteúdo do URL com o que for informado no conteúdo do body.
const url = 'https://jsonplaceholder.typicode.com/posts/1/';

fetch(url, {
  method: 'PUT',
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
  body: '{"titulo": "JavaScript"}'
})
.then(r => r.json())
.then(r => console.log(r))
  • HEAD
    • HEAD puxa apenas os headers. É uma requisição mais leve pois não puxa o body.
const url = 'https://jsonplaceholder.typicode.com/posts/1/';

fetch(url, {
  method: 'HEAD',
})
.then(response => {
  response.headers.forEach(console.log);
  console.log(response.headers.get('Content-Type'));
});
  • HEADERS

    • Cache-Control
      • Tempo que o arquivo deve ficar em cache em segundos. Ex: public, max-age=3600
    • Content-Type
      • Tipo de conteúdo. Ex: text/html; charset=utf-8. Indicar o tipo de arquivo principalmente em métodos POST e PUT.
    • Lista de Headers
  • CORS

    • Cross-Origin Resource Sharing, gerencia como deve ser o compartilhamento de recursos entre diferente origens.
    • É definido no servidor se é permitido ou não o acesso dos recursos através de scripts por outros sites. Utilizando o Access-Control-Allow-Origin.
    • Se o servidor não permitir o acesso, este será bloqueado. É possível passar por cima do bloqueio utilizando um proxy.
    • CORS é um acordo entre browser / servidor ou servidor / servidor. Ele serve para dar certa proteção ao browser, mas não é inviolável.
const url = 'https://cors-anywhere.herokuapp.com/https://www.google.com/';
const div = document.createElement('div');

fetch(url)
.then(r => r.text())
.then(r => {
  div.innerHTML = r;
  console.log(div);
});
  • JAVASCRIPT ASSÍNCRONO
    • FETCH API
      • Permite fazermos requisições HTTP através do método fetch(). Este método retorna a resolução de uma Promise. Podemos então utilizar o then para interagirmos com a resposta, que é um objeto do tipo Response.
fetch('./arquivo.txt').then(function(response) {
  console.log(response); // Response HTTP (Objeto)
});
  • RESPONSE
    • O objeto Response, possui um corpo com o conteúdo da resposta. Esse corpo pode ser transformado utilizando métodos do protótipo do objeto Response. Estes retornam outras promises.
fetch('./arquivo.txt').then(function(response) {
  return response.text();
}).then(function(corpo) {
  console.log(corpo);
});
  • SERVIDOR LOCAL
    • O fetch faz uma requisição HTTP/HTTPS. Se você iniciar um site local diretamente pelo index.html, sem um servidor local, o fetch não irá funcionar.
fetch('c:/files/arquivo.txt')
.then((response) => {
  return response.text();
})
.then((corpo) => {
  console.log(corpo);
}); // erro
  - Se dermos um espaço após o objeto ou pularmos linha, o método continua funcionando.
  • .JSON()
    • Um tipo de formato de dados muito utilizado com JavaScript é o JSON (JavaScript Object Notation), pelo fato dele possuir basicamente a mesma sintaxe que a de um objeto js. .json() transforma um corpo em json em um objeto JavaScript.
fetch('https://viacep.com.br/ws/01001000/json/')
.then(response => response.json())
.then(cep => {
  console.log(cep.bairro, cep.logradouro);
});
  • .TEXT()
    • Podemos utilizar o .text() para diferentes formatos como txt, json, html, css, js e mais.
const styleElement = document.createElement('style');

fetch('./style.css')
.then(response => response.text())
.then(style => {
  styleElement.innerHTML = style;
  document.body.appendChild(styleElement);
});
  • HTML E .TEXT()
    • Podemos pegar um arquivo inteiro em HTML, transformar o corpo em texto e inserir em uma div com o innerHTML. A partir dai podemos manipular esses dados como um DOM qualquer.
const div = document.createElement('div');

fetch('./sobre.html')
.then(response => response.text())
.then(htmlBody => {
  div.innerHTML = htmlBody;
  const titulo = div.querySelector('h1');
  document.querySelector('h1').innerText = titulo.innerText;
});
  • .BLOB() -Um blob é um tipo de objeto utilizado para representação de dados de um arquivo. O blob pode ser utilizado para transformarmos requisições de imagens por exemplo. O blob gera um URL único.
const div = document.createElement('div');

fetch('./imagem.png')
.then(response => response.blob())
.then(imgBlob => {
  const blobUrl = URL.createObjectURL(imgBlob);
  console.log(blobUrl);
});
  • .CLONE()
    • Ao utilizarmos os métodos acima, text, json e blob, a resposta é modificada. Por isso existe o método clone, caso você necessite transformar uma resposta em diferentes valores.
const div = document.createElement('div');

fetch('https://viacep.com.br/ws/01001000/json/')
.then(response => {
  const cloneResponse = response.clone();
  response.json().then(json => {
    console.log(json)
  });
  cloneResponse.text().then(text => {
    console.log(text)
  });
});
  • .HEADERS
    • É uma propriedade que possui os cabeçalhos da requisição. É um tipo de dado iterável então podemos utilizar o forEach para vermos cada um deles.
const div = document.createElement('div');

fetch('https://viacep.com.br/ws/01001000/json/')
.then(response => {
  response.headers.forEach(console.log);
});
  • .STATUS E .OK
    • Retorna o status da requisição. Se foi 404, 200, 202 e mais. ok retorna um valor booleano sendo true para uma requisição de sucesso e false para uma sem sucesso.
const div = document.createElement('div');

fetch('https://viacep.com.br/ws/01001000/json/')
.then(response => {
  console.log(response.status, response.ok);
  if(response.status === 404) {
    console.log('Página não encontrada')
  }
});
  • .URL E .TYPE
    • .url retorna o url da requisição. .type retorna o tipo da reposta.
const div = document.createElement('div');

fetch('https://viacep.com.br/ws/01001000/json/')
.then(response => {
  console.log(response.type, response.url);
});
//types
// basic: feito na mesma origem
// cors: feito em url body pode estar disponível
// error: erro de conexão
// opaque: no-cors, não permite acesso de outros sites
  • ASYNC / AWAIT
    • A palavra chave async indica que a função possui partes assíncronas e que você pretende esperar a resolução da mesma antes de continuar. O await irá indicar a promise que devemos esperar. Faz parte do ES8.
async function puxarDados() {
  const dadosResponse = await fetch('./dados.json');
  const dadosJSON = await dadosResponse.json();
  
  document.body.innerText = dadosJSON.titulo;
}

puxarDados();
  • THEN / ASYNC
    • A diferença é uma sintaxe mais limpa.
function iniciarFetch() {
  fetch('./dados.json')
  .then(dadosResponse => dadosResponse.json())
  .then(dadosJSON => {
    document.body.innerText = dadosJSON.titulo;
  })
}
iniciarFetch();


async function iniciarAsync() {
  const dadosResponse = await fetch('./dados.json');
  const dadosJSON = await dadosResponse.json();
  document.body.innerText = dadosJSON.titulo;
}
iniciarAsync();
  • TRY / CATCH
    • Para lidarmos com erros nas promises, podemos utilizar o try e o catch na função.
async function puxarDados() {
  try {
    const dadosResponse = await fetch('./dados.json');
    const dadosJSON = await dadosResponse.json();
    document.body.innerText = dadosJSON.titulo;
  }
  catch(erro) {
    console.log(erro);
  }
}
puxarDados();
  • INICIAR FETCH AO MESMO TEMPO
    • Não precisamos esperar um fetch para começarmos outro. Porém precisamos esperar a resposta resolvida do fetch para transformarmos a response em json.
async function iniciarAsync() {
  const dadosResponse = fetch('./dados.json');
  const clientesResponse = fetch('./clientes.json');

  // ele espera o que está dentro da expressão () ocorrer primeiro
  const dadosJSON = await (await dadosResponse).json();
  const clientesJSON = await (await clientesResponse).json();
}
iniciarAsync();
  • PROMISE
    • O resultado da expressão à frente de await tem que ser uma promise. E o retorno do await será sempre o resultado desta promise.
async function asyncSemPromise() {
  // Console não irá esperar.
  await setTimeout(() => console.log('Depois de 1s'), 1000);
  console.log('acabou');
}
asyncSemPromise();

async function iniciarAsync() {
  await new Promise(resolve => {
    setTimeout(() => resolve(), 1000)
  });
  console.log('Depois de 1s');
}
iniciarAsync();

learning-javascript's People

Contributors

alexgalhardo avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.