【发布时间】:2017-11-25 06:32:48
【问题描述】:
我想从 REST api 获取响应数据。 我的本地主机网址:
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");
请帮帮我..谢谢..
【问题讨论】:
-
尝试使用
success()回调而不是then() -
自 Angular 1.4 以来已弃用成功。它不会工作
-
您是否在控制台窗口中遇到任何错误?
-
在处理响应时尝试使用
$scope.welcome = response;而不是$scope.welcome = response.data;。 -
没有不工作...@RahulSharma
标签: html angularjs node.js web-services http