Angularjs controller cannot access nodejs port 3000, cross-origin access, angularjsnodejs
Currently, a project uses angularjs as the front end and nodejs as the backend server.
I tried to use the following method to initiate a request to the nodejs Server:
$http.get('http://localhost:3000/') .success(function (data) { $scope.index = data; }) .error(function (data) { $scope.index = ""; });</span>
The server I simplified is as follows:
var app= require('express');/* GET home page. */app.get('/', function(req, res, next) { res.send("hello world");});
In the IE 11 browser, hello world can be returned successfully, but Firefox and Chrome cannot be returned. F12 opens the debugger and finds that cross-origin access is caused by browser protection.
My solution is to use CORS (Cross Origin Resource Sharing (CORS) as a good way to solve Cross-Origin problems.
You can use XHR to load data and resources from different sources .)
// Nodejs Server Cross-origin access settings
app.use(function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Credentials', true); res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'); next();});
Then, Firefox and Chrome can be accessed successfully.
I think the following articles have greatly helped me solve this problem and I recommend them to you:
Http://my.oschina.net/blogshi/blog/303758
Http://zhuanlan.zhihu.com/FrontendMagazine/19920223
Http://www.cnblogs.com/idche/p/3190926.html