Issue
I am creating a micro server node JS only using native node http. But only when I do post the form is returned me a cors a error.
Follow the below code I'm writing:
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-Headers", "Origin, X-Requested-With, Content-Type, Accept")
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':
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
var queryData = '';
req.on('data', function(data) {
queryData += data;
});
req.on('end', function() {
var obj = querystring.parse(queryData);
contatos.push(obj);
});
res.writeHead(200, {'Content-Type' : 'application/json'});
res.end('Objeto inserido.');
break;
default:
res.writeHead(400, {'Content-Type' : 'application/json'});
res.end('Rota não encontrada');
}
}).listen(3000, function () {
console.log('server run on 3000');
});
Follow the instructions below to share angular with http post:
$scope.adicionarContato = function(contato) {
console.log(contato);
contato.data = new Date();
$http.post("http://localhost:3000/contatos/inserir", contato).success(function (data) {
});
delete $scope.contato;
$scope.contatoForm.$setPristine();
};
And now the error that is returned in the browser:
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
fromJson@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:1252:9
defaultHttpResponseTransform@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:9414:1
transformData/<@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:9505:12
forEach@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:336:11
transformData@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:9504:3
transformResponse@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:10276:23
processQueue@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:14745:28
scheduleProcessQueue/<@file:///home/tiago/Dropbox/branas_angularjs/lib/angular/angular.js:14761:27
$RootScopeProvider/this.$get
This code on gist: https://gist.github.com/tiagoeborsanyi/0d2992c67d4cd57f0db5 If someone can help me, I'm already two days ago caught it. : ( Thanks.
Solution
This isn't a CORS error. There's something wrong in the code. Try debugging your angular code with Chrome's developer tools. Also, check your node logs for errors there.
The most common CORS error you will encounter will look like this:
XMLHttpRequest cannot load http://some.api/endpoint. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://origin.youre/calling/api/from' is therefore not allowed access.
CORS errors typically list the requested domain and the requesting domain along with an explanation of the error. Learn more about CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Answered By - styonsk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.