首先你应该了解http请求的流程。
这是一个使用 Angular 内置工具 $resource 的示例。
以下是我从视图中的搜索文本框中将用户正在寻找的内容作为参数发送的搜索功能的表示:
// :search is the param
angular.module("MyApp")
.factory("Search", function($resource) {
return $resource("/api/search/:search", {}, {
query : {
method : "GET",
isArray : true
}
});
});
这是控制器:
所有这些控制器所做的就是观察是否有用户输入输入文本以进行搜索,并获取用户正在编写的内容并将其发送到后端,与上面的工厂/服务一起工作。此功能将数据发送到后端以获取查询,该查询是搜索结果的数组。
angular.module('MyApp')
.controller('AddCtrl', function($scope, $alert, Show, Search) {
$scope.showName = '';
$scope.data = {};
$scope.addShowToModel = '';
$scope.$watch('showName', function (tmpStr) {
if (!tmpStr || tmpStr.length == 0) return 0;
if (tmpStr === $scope.showName) {
Search.query({ 'search': $scope.showName })
.$promise.then(function(data) {
$scope.responseData = data;
})
.catch(function(response) {
console.log(response.error);
});
}
});
});
这里是来自 Nodejs 的代码:
app.get('/api/search/:search', function(req, res, next) {
var searchParam = req.params.search
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
var parser = xml2js.Parser(); // npm module to convert xml to json
request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + searchParam, function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
if (result.Data.Series !== undefined) {
// this is how you send the data to the frontend
return res.status(200).send(result.Data.Series);
} else {
res.status(411).send({message: searchParam + " wasn't found"});
}
});
});
});
所以,简单地说:
app.post('/', function(req, res){
var body = req.body;
console.log(body);
return res.send(//whatever you need to send);
};
有时您不想将数据发送到前端,而是发送状态码以查看操作的进行情况:
app.post('/', function(req, res){
if(everythingIsFine) {
// send only status code
res.sendStatus(200);
}else {
// in case you want to send status + message
res.status(401).send('Invalid whatever thing');
}
};
希望对你有帮助!
编辑
在服务中,您可以使用$http 代替$resource。这不是我回答的重要内容,只是告诉你。根据评论:
使用 $http.get 代替 $resource 会更合适。 $resource 用于 RESTful CRUD 端点。搜索端点不符合该规范。