Skip to content

Instantly share code, notes, and snippets.

@tiagoeborsanyi
Created February 25, 2016 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagoeborsanyi/0d2992c67d4cd57f0db5 to your computer and use it in GitHub Desktop.
Save tiagoeborsanyi/0d2992c67d4cd57f0db5 to your computer and use it in GitHub Desktop.
Micro servidor nodejs para get e post usando somente http nativo do nodejs
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var contatos = [
{nome: "Bruno", telefone: "9999-2222", data: new Date(), operadora: {nome: "Oi", codigo: 14, categoria: "Celular"}},
{nome: "Sandra", telefone: "9999-3333", data: new Date(), operadora: {nome: "Vivo", codigo: 15, categoria: "Celular"}},
{nome: "Mariana", telefone: "9999-9999", data: new Date(), operadora: {nome: "Tim", codigo: 41, categoria: "Celular"}}
];
var operadoras = [
{nome: "Oi", codigo: 14, categoria: "Celular", preco: 2},
{nome: "Vivo", codigo: 15, categoria: "Celular", preco: 1},
{nome: "Tim", codigo: 41, categoria: "Celular", preco: 3},
{nome: "GVT", codigo: 25, categoria: "Fixo", preco: 1},
{nome: "Embratel", codigo: 21, categoria: "Fixo", preco: 2}
];
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = true;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept";
http.createServer(function (req, res) {
var url_parts = url.parse(req.url);
switch(url_parts.pathname) {
case '/contatos':
res.setHeader('Access-Control-Allow-Origin', '*');
//res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
//res.header('Access-Control-Allow-Headers', 'Content-Type');
res.writeHead(200, {'content-Type': 'application/json'});
res.end(JSON.stringify(contatos));
break;
case '/operadoras':
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.writeHead(200, {'content-Type': 'application/json'});
res.end(JSON.stringify(operadoras));
break;
case '/contatos/inserir':
var queryData = '';
req.on('data', function(data) {
queryData += data;
});
req.on('end', function() {
var obj = querystring.parse(queryData);
contatos.push(obj);
console.log(req.socket._events.end);
res.writeHead(200, headers);
res.end('Objeto inserido.');
});
default:
res.writeHead(400, {'Content-Type' : 'application/json'});
res.end('Rota não encontrada');
}
}).listen(3000, function () {
console.log('server run on 3000');
});
@tiagoeborsanyi
Copy link
Author

case '/contatos/inserir':
var queryData = '';
req.on('data', function(data) {
queryData += data;
});
req.on('end', function() {
var obj = querystring.parse(queryData);
contatos.push(obj);
console.log(req.socket._events.end);
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
res.writeHead(200, {'Content-Type' : 'application/json'});
res.end('Objeto inserido.');
});

@tiagoeborsanyi
Copy link
Author

Error: h

OPTIONS
XHR
http://localhost:3000/contatos/inserir [HTTP/1.1 400 Bad Request 2ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/contatos/inserir. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

@ivieira
Copy link

ivieira commented Feb 25, 2016

Vi sua dúvida no grupo do Be MEAN.
Já tentou fazer assim:

app.all('', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '
');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTION S');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});

@tiagoeborsanyi
Copy link
Author

Mas desse jeito seria usando express? isso?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment