Angularjs controller cannot access nodejs port 3000, cross-origin access

Source: Internet
Author: User

Angularjs controller cannot access nodejs port 3000, cross-origin access

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 = ;                });

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.

 

 



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.