Angularjs http get 请求返回“长度”错误
2017-04-27
845
我是 Angularjs 和 MongoDB 的新手,我需要从 MongoDB 发送 HTTP 请求,以便自动完成角度材料,当我发送到 git hub API 时,它工作正常,但对于我的数据库,我得到“无法读取未定义的属性‘长度’” 我的客户端控制器
/*jslint latedef:false*/
(function () {
'use strict';
angular
.module('clientApp')
.controller('CarnetCtrl', function($http){
this.querySearch = function(query){
//for this link work "https://api.github.com/search/users"
return$http.get("http://localhost:3000/carnet/export_countries/", {
params: {
q: query
}
}).then(function(response){
return response.data.items;
});
};
});
})();
我的 Mongodb 控制器
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Q = require('q'); // We can now use promises!
//Create Schema
var CarnetExportCountriesSchema = new Schema({
CarnetExportCountriesSchema.statics.getCarnetExportCountries = function(Country_Name_EN) {
var deferred = Q.defer();
this.findOne({Country_Name_EN: Country_Name_EN}, function(error, CarnetExportCountries){
if (error) {
deferred.reject(new Error(error));
}
else {
deferred.resolve(manufacturers);
}
});
return deferred.promise;
}
CarnetExportCountriesSchema);
module.exports = CarnetExportCountriesSchema;
和 index.js 服务器端:
//Add Middleware necessary for REST API's
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({type:'application/vnd.api+json'}));
app.use(methodOverride('X-HTTP-Method-Override'));
//CROS Support
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers','Content-Type');
res.header('("Content-Length", ""+json.length() );');
next();
});
我的 app.js
.config(function (
$routeProvider,
RestangularProvider
) {
RestangularProvider.setBaseUrl('http://localhost:3000');
$routeProvider
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
controllerAs: 'main'
})
我的错误:
TypeError: Cannot read property 'length' of undefined
at hasMatches (angular-material.js:25423)
at shouldShow (angular-material.js:25415)
at shouldHide (angular-material.js:25380)
at setLoading (angular-material.js:25371)
at angular-material.js:25564
at handleCallback (angular.js:17010)
at angular.js:16825
at processQueue (angular.js:16843)
at angular.js:16887
at Scope.$digest (angular.js:17982) "Possibly unhandled rejection: {}"
请帮助我解决这个问题,我搜索并阅读了大约 1 周,但无法解决这个问题
2个回答
尝试删除
res.header('("Content-Length", ""+json.length() );');
Leibale Eidelman
2017-04-27
请检查
return$http.get
是否写成一个单词(return 和 $http 之间有空格)并在响应处进行检查
if(response && response.data && response.data.items){
return response.data.items
}
return [];
Taner Melikoglu
2017-04-27