我正在创建一个微服务器 NodeJS 只使用本机节点http。但只有当我做后的形式是返回给我一个cors一个错误。
下面是我写的代码:
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');
});
按照以下说明与http post共享Angular :
$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();
};
现在浏览器中返回的错误是:
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
$根作用域提供程序/this.$get
这部法典的要旨在于:https://gist.github.com/tiagoeborsanyi/0d2992c67d4cd57f0db5如果有人能帮助我,我两天前就已经抓住了它.格:(谢谢。
2条答案
按热度按时间cbeh67ev1#
这不是CORS错误。代码中有错误。尝试使用Chrome的开发者工具调试Angular 代码。另外,检查节点日志中的错误。
最常见的CORS错误如下所示:
XMLHttpRequest无法加载http://some.api/endpoint。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“http://origin.youre/calling/api/from”。
CORS错误通常会列出所请求的域和请求域沿着错误说明。在此处了解有关CORS的更多信息:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
xsuvu9jc2#
这是因为在您的节点服务器上,您必须允许与客户端平台共享资源。
为了更好地理解,您可以参考视频,它在1分钟内解决了这个问题。
https://youtu.be/BVwZAr04bkc