ANGULARJS controller cannot access Nodejs 3000 ports, cross-domain access

Source: Internet
Author: User

Currently do a project, the front-end is Angularjs, the backend Nodejs do the server.

I tried to initiate a request to the NODEJS server using the following method:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >           $http. Get (' http://localhost:3000/')                . Success (function (data) {                  $scope. index = data;                })                . Error (function (data) {                   $scope. Index = "";                }); </span>

Server-side I simplified as follows:

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >var app= require (' Express ');/* GET home page. */app.get ('/', function (req, res, next) {    res.send ("Hello World");}); </span>

With IE11 Browser, can successfully return Hello World, but Firefox and Chrome but not, F12 open the debugger, found that cross-domain access caused by, belong to the browser protection mechanism.

My solution is that using CORS (cross Origin Resource sharing,cors) is a good way to solve cross-domain problems and
You can use XHR to load data and resources from different sources. )

Nodejs server-side cross-domain access settings

<span style= "FONT-FAMILY:SIMHEI;FONT-SIZE:18PX;" >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 ();}); </span>


Then, Firefox and Chrome will be able to access it successfully.


I think the following articles, for me to solve this problem a lot of help, recommend to everyone:

http://my.oschina.net/blogshi/blog/303758

http://zhuanlan.zhihu.com/FrontendMagazine/19920223

Http://www.cnblogs.com/idche/p/3190926.html




ANGULARJS controller cannot access Nodejs 3000 ports, cross-domain access

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.