gpt4 book ai didi

node.js - 在 POST 上获取 ng-model 值到 Express.js 端点

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:02 26 4
gpt4 key购买 nike

我正在使用 AngularJS 创建 Node.js 应用程序。

我想使用 Angular 进行一个简单的 POST。此 POST 应该将几个值发布到我的服务器,我可以在其中使用 console.log 查看它们。

在我的 HTML 代码中,我使用 ng-model 和一个具有 ng-click 的按钮构建它。

我可以知道我的 Node.js 服务器受到了攻击,因为它在控制台中输出了名为的帖子。

但是,我一直在尝试了解如何读取 POST 值,但尚未找到解决方案。

如何修改代码以读取 Express.js 端点中的 serialKeygameTitle

我的 HTML 代码:

<div class="input-group" ng-controller="CreateController">
<p>Serial key:<br/>
<input class="form-control" ng-model="serialKey" />
</p>

<p>Game:<br/>
<input class="form-control" ng-model="gameTitle" />
</p>

<span class="input-group-btn">
<button class="btn btn-default"
ng-click="postNewIsbn(serialKey,gameTitle)">Add</button>
</span>
</div>

Angular Controller 代码:

app.controller('CreateController',function($scope, $http) {
var url = '/api/serials';
$scope.postNewIsbn = function(serial, game) {
$http.post(url, {
serial: serial,
gametitle: game
})
.success(function (data) {
$scope.data.status = 'success';
})
.error(function(error) {
$scope.data.error = error;
});
};
});

Express.js 端点

app.post('/api/serials',function(req,res){

console.log(req.body);
console.log('post called');
});

最佳答案

这似乎是设置内容类型 header 的问题。在您的 Angular 应用程序中,您可以在初始化模块后或使用此行在配置函数中为您的发布请求设置defaultHeaders

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

无论您在何处设置此 header ,请记住注入(inject) $httpProvider 依赖项

更新

您可能需要配置 Express 才能将 bodyParser 与此行一起使用:

app.use(express.bodyParser());

关于node.js - 在 POST 上获取 ng-model 值到 Express.js 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24995388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com