angularjs http请求到nodejs api

时间:2017-05-16 20:23:52

标签: angularjs node.js http server

使用NodeJ我已经设置了一个有效的API(我可以在浏览器中看到JSON结果)。在Angular中,我有一个socket.io聊天,它通过端口3030上的http运行。我还运行一个apache服务器(带有xampp),它服务于AngularJs的前端。

只要我想从Angularjs向Nodejs API发出请求,我就会在浏览器控制台中收到以下错误

XMLHttpRequest cannot load localhost:3030/api/feed. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

据我在谷歌搜索后所理解的是,只要我没有在NodeJS中运行HTTP服务器,Angular就无法与API通信。 但是我可以在同一个进程中为api运行socket.io服务器和HTTP服务器吗?

server.js



var express = require('express');
var app = express();
var http    = require('http').Server(app);
var io = require('socket.io')(http);

var routes  =   require('./app/api/routes');
app.use('/api', routes);

var chatMembers = {};


io.on('connection', function(socket){

	socket.on("new-message", function(msg){
		console.log(msg);
		var username = msg[username];
		var message = msg[message];
		io.emit("receive-message", msg);
	})

	socket.on("new-connection", function(username){
		chatMembers[socket.id] = username;
		console.log(chatMembers);

		io.emit("online-list", createOnlineList());
	})

	socket.on("disconnect", function(){
		if(chatMembers[socket.id] != undefined){
			console.log(" " + chatMembers[socket.id] + " hat die Verbindung getrennt.");
			delete chatMembers[socket.id];
			io.emit("online-list", createOnlineList());
		}
	})
});


function createOnlineList(){
	//returns list of every member connected to the socket (only name)
  	var onlinelist = [];
	for(var index in chatMembers){
		onlinelist.push(chatMembers[index]);
	}
	return onlinelist;
}


http.listen('3030', function(){
  console.log("Server online");
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
&#13;
&#13;
&#13;

controller.js

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
angular.module('coursemate')
    .controller("chatCtrl", ['$rootScope','$scope', '$http', function($rootScope, $scope, $http){
		var vm = this;
		var socket = window.io('localhost:3030/');
		vm.newMessage = undefined;
		vm.username = undefined;
		vm.messages = [];
		vm.onlinelist = [];
		vm.sendBtnDisabled = true;
		vm.connected = false;


		//socket acions
		socket.on("receive-message", function(msg){
			//socket server send message to us
			$scope.$apply(function(){
			  vm.messages.push(msg);
			});
		});

		socket.on("online-list", function(list){
			//server sends us refreshed list of members
			$scope.$apply(function(){
			  vm.onlinelist = list;
			});
		});

		socket.on('disconnect', function(){
			//connection failed
			vm.connected = false;
			vm.keyEventSendMessage(null);
		});

		socket.on('connect', function(){
			//connection established
			vm.connected = true;
			vm.keyEventSendMessage(null);
		});
		vm.username = undefined;



		vm.sendMessage = function(){
			//we send messsage to socket server
			var newMessage = {
				username: vm.username,
				message: vm.newMessage
			};
			socket.emit("new-message", newMessage);

			var config = {
                headers : {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
                }
            }
            var data = $.param({
                user: vm.username,
                content: vm.newMessage
            });
			$http.post('app/database/database.php?req=1', data, config).success(function(data) {
	       	});

	        vm.newMessage = undefined;
	        vm.keyEventSendMessage(null);
		};

		vm.createUser = function(username){
			// we "log in" as users
			vm.username = username;
			socket.emit("new-connection", username);
		}
 		vm.keyEventSendMessage = function(event){
 			//fired on keyhit at message input
 			if(typeof(vm.newMessage) != 'undefined' && vm.newMessage != null && vm.newMessage != '' && vm.connected){
 				vm.sendBtnDisabled = false;
 				if(event != null && event.keyCode == 13){
 					vm.sendMessage();
 				}
 			}else{
 				vm.sendBtnDisabled = true;
 			}
 		}

		$http.get('localhost:3030/api/feed').success(function(data) {
			console.log(data);
		});

    }]);
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

这是由于CORS政策,正如Julian Soro所指出的那样。

在我的虚拟机上测试并访问主机上的API之前,我正在处理此问题。如果您使用的是Chrome,可能会提到有一个扩展可以解决这个问题。您可以下载此扩展程序以允许Chrome上的CORS。 Here是指向&#39; Allow-Control-Allow-Origin的链接:*&#39;。

希望这可以提供帮助。