我尝试使用 Angular.js 通过 POST 方法发送两个输入值,但我无法在 URL 上传递这些值,甚至无法在服务器端捕获它们。 有人可以帮我解决这个问题吗?
对于每个按钮,我需要传递两个值+按钮值(operacao)
表单
<form id="form" ng-controller="Controller">
<input id="val1" name="val1" ng-model="val1" placeholder="Valor 1" type="text">
<input id="val2" name="val2" ng-model="val2" placeholder="Valor 2" type="text">
<input id="operacao" name="operacao" type="hidden" value="0">
<input id="soma" type="button" value="soma" ng-click="doClick(val1, val2)">
<input id="sub" type="button" value="sub">
<input id="mult" type="button" value="mult">
<input id="divs" type="button" value="divs">
<input id="resultado" type="text">
</form>
Controller
.controller("Controller", function($scope, operacaoService) {
$scope.model = {};
$scope.doClick = function(operacao) {
$scope.model.operacao = operacao;
operacaoService.postOperacao($scope.model)
.success(function(data, status) {
$scope.valores = data.result;
console.log(data.result);
})
.error(function(data, status) {
console.log("erro", status);
});
};
})
服务
module.factory('operacaoService', function($http) {
var postOperacao = function(model) {
return $http({
url: "/operacoes",
method: "post",
params: model
});
};
return {
postOperacao: postOperacao
};
});
<小时/>
服务器(Node.js)
app.post('/operacoes', function(req, res) {
var valores = req.query;
var val1 = parseInt(valores.val1);
var val2 = parseInt(valores.val2);
var operacao = (valores.operacao);
var result;
if (operacao === "soma") {
result = val1 + val2;
res.send({
result: result,
val1: val1,
val2: val2,
operacao: operacao
});
}
}
最佳答案
根据https://docs.angularjs.org/api/ng/service/ $http#usage 看起来您正在使用配置对象的错误属性来设置数据负载。 params 属性用于 GET 请求。
在您的服务中,尝试按如下方式编辑 $http 调用:
module.factory('operacaoService', function($http) {
var postOperacao = function(model) {
return $http({
url: "/operacoes",
method: "post",
data: model
});
};
return {
postOperacao: postOperacao
};
});
此外,在您的服务器端,您似乎正在使用express。而不是使用
var valores = req.query
将其更改为:
var valores = req.body
关于javascript - 使用 Angular.js 使用 POST 方法发送输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34931327/