我正在学习AngularJS,我想知道如何使用ExpressJS正确连接Node。ExpressJS AngularJS POST
这是我的控制器:
app.controller('view1Ctrl', function($scope, $http) {
$scope.sub = function(desc) {
console.log(desc);
$http.post('/view1', desc).
then(function(response) {
console.log("posted successfully");
}).catch(function(response) {
console.error("error in posting");
})
}
});
这是我server.js:
app.post('/view1', function(req, res) {
console.log(res.desc);
res.end();
});
我没有用身体解析器。当我在控制器中使用一个函数时,我没有得到如何使用body-parser从html获取表单值。在使用body-parser时,点击提交时的值是从html获得的,还是从我传递表单值作为参数的函数获取值?请告诉我它是如何完成的。
编辑:这是我的html:
<form>
<input type="text" ng-model="desc" placeholder="Enter desc" />
<button class="btn btn-primary" ng-click="sub(desc)">Submit</button>
</form>
编辑2: 全server.js代码:
var express = require('express'),
http = require('http'),
path = require('path'),
bodyParser= require('body-parser');
var app = express();
app.set('port', 3000);
app.use(express.static(path.normalize(__dirname + '/')));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/main', function(req, res) {
var name = 'MyNameFromServer';
res.send(name);
});
app.post('/view1', function(req, res) {
console.log(res.body.desc);
res.end();
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
编辑3: 编辑控制器app.js
app.controller('view1Ctrl', function($scope, $http) {
$scope.sub = function() {
console.log($scope.formData);
$http.post('/view1', $scope.formData).
success(function(data) {
console.log("posted successfully");
}).error(function(data) {
console.error("error in posting");
})
};
});
如何点击按钮?它是否应该再次通过desc,或者我是否必须通过任何传递来调用它? – v1shnu
你不需要它,你有'$ scope'我正在更新答案。 –
经过所有的修改后,它说TypeError:无法读取undefined属性'desc'.. – v1shnu