Angularjs我无法从HTTP localhost调用获取响应数据

时间:2017-06-22 06:20:44

标签: html angularjs node.js web-services http

我想从REST api获取响应数据。 我的Localhost URL:

http://localhost:3000/welcome

我的AngularJs代码:

<!DOCTYPE html>
<html>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl"> 
<h1>{{welcome}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("http://localhost:3000/welcome")
    .then(function(response) {
       $scope.welcome = response.data;
  });
});
</script>

</body>
</html>

响应数据未显示在h1标记中。 我已经在邮递员的工作中对这个APi进行了测试。

这是我的Nodejs服务器代码:

var express = require('express');
var app = express();

app.get('/welcome', function(req,res) {
    res.send("Welcome to Nodejs");

});

app.use(function (req, res, next) {

     // Website you wish to allow to connect
     res.setHeader('Access-Control-Allow-Origin', '*');

     // Request methods you wish to allow
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

     // Request headers you wish to allow
     res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

     // Set to true if you need the website to include cookies in the requests sent
     // to the API (e.g. in case you use sessions)
     res.setHeader('Access-Control-Allow-Credentials', true);

     // Pass to next layer of middleware
     next();
 }); 

app.listen(3000, "localhost");

请帮帮我..谢谢..

1 个答案:

答案 0 :(得分:1)

我认为这可能是由于CORS造成的。否则,你的代码似乎没问题。在Express服务器中添加以下Access-Control-Allow-Origin标头并尝试使用。

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});