angularjs 控制器不能訪問nodejs 3000連接埠,跨域訪問

來源:互聯網
上載者:User

angularjs 控制器不能訪問nodejs 3000連接埠,跨域訪問

目前做的一個項目,前端採用的是angularjs,後端nodejs做伺服器。

我嘗試使用接下裡的方式來發起對nodejs伺服器的請求:

 

 $http.get('http://localhost:3000/')                .success(function (data) {                  $scope.index = data;                })                .error(function (data) {                   $scope.index = ;                });

伺服器端我簡化如下:

 

 

var app= require('express');/* GET home page. */app.get('/', function(req, res, next) {    res.send(hello world);});

使用IE11瀏覽器,能夠成功返回hello world,但是Firefox和Chrome卻不能,F12開啟調試器,發現是跨域訪問造成的,屬於瀏覽器保護機制。

 

我的解決辦法是,是使用CORS( 跨域資源共用(Cross Origin Resource Sharing,CORS)是一個解決跨域問題的好方法,從而
可以使用XHR從不同的源載入資料和資源。)

//nodejs服務端跨域訪問設定

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

 

 

然後,Firefox和Chrome就可以成功訪問了。

 

 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.