node.js ExpressJS AngularJS POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31119605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:55:56  来源:igfitidea点击:

ExpressJS AngularJS POST

angularjsnode.jsexpress

提问by v1shnu

I'm learning AngularJS and I want to know how to correctly wire it with Node with ExpressJS.

我正在学习 AngularJS,我想知道如何使用 ExpressJS 将它与 Node 正确连接。

This is my controller:

这是我的控制器:

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");
        })
    }
});

And this is my server.js:

这是我的 server.js:

app.post('/view1', function(req, res) {
    console.log(res.desc);
    res.end();
});

I have not used body-parser. I don't get how body-parser is used to get the form values from the html when I am using a function in controller. Does the values got from the html on clicking submit when using body-parser or does the values are got from the function on which I am passing the form values as arguments. Please tell me how it is done .

我没有使用过body-parser。当我在控制器中使用函数时,我不明白如何使用 body-parser 从 html 获取表单值。使用 body-parser 时单击提交时是否从 html 中获取值,或者是否从我将表单值作为参数传递的函数中获取值。请告诉我它是如何完成的。

EDIT:this is my html:

编辑:这是我的 html:

<form>
      <input type="text" ng-model="desc" placeholder="Enter desc" />
      <button class="btn btn-primary" ng-click="sub(desc)">Submit</button>
</form>

EDIT 2:full server.js code:

编辑 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'));
});

EDIT 3:Edited Controller app.js

编辑 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");
        })
    };
});

回答by michelem

The body-parser module for Node.js (Express) can get every data from your form post into a single object called req.body, so if you have a $scopeobject to define your form data you can inject directly that to have the same properties copied on req.body:

Node.js (Express) 的 body-parser 模块可以将表单发布中的每个数据放入一个名为 的对象中req.body,因此如果您有一个$scope对象来定义表单数据,您可以直接注入该对象,以便在 req 上复制相同的属性。身体:

Angular:

角度:

app.controller('view1Ctrl', function($scope, $http) {
    $scope.sub = function() {
        $http.post('/view1',$scope.formData).
        then(function(response) {
            console.log("posted successfully");
        }).catch(function(response) {
            console.error("error in posting");
        })
    }
});

HTML:

HTML:

<form>
      <input type="text" ng-model="formData.desc" placeholder="Enter desc" />
      <input type="text" ng-model="formData.title" placeholder="Enter title" />
      <button type="submit" class="btn btn-primary" ng-click="sub()">Submit</button>
</form>

Now when you submit it via $http.post('/view1', $scope.formData)you will get the same object, for example:

现在,当您通过它提交时,$http.post('/view1', $scope.formData)您将获得相同的对象,例如:

app.post('/view1', function(req, res) {
    console.log(req.body.desc);
    res.end();
});

Instead having an ng-click on the submit button, you could also use ng-submitin the form element like this:

除了在提交按钮上单击 ng,您还可以ng-submit在表单元素中使用,如下所示:

<form ng-submit="sub()">

回答by Shankar Regmi

First of all you should be aware of two global variable reqand res.

首先,您应该了解两个全局变量reqres.

when you hit post request req.bodycatches the request from httpand body-parserextracts the raw content from post request.

当您点击发布请求时,会req.body捕获来自发布请求的请求httpbody-parser从发布请求中提取原始内容。

app.post('/view1', function(req, res) {
 console.log(req.body.desc);
 res.end();
});

before using it you must include

在使用它之前,你必须包括

var bodyParser = require('body-parser');

and include middleware as

并将中间件包括为

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing       application/x-www-form-urlencoded

more about middleware, reqand resplease refer to

详细了解middlewarereqres请参阅

http://expressjs.com/4x

http://expressjs.com/4x