简体   繁体   English

数据未从AngularJS控制器传递到NodeJS服务器

[英]Data is not passed from AngularJS controller to NodeJS server

I am attempting to pass some values from my client-side AngularJS script to a server-side NodeJS script. 我试图将一些值从客户端AngularJS脚本传递到服务器端NodeJS脚本。 I set up the POST request like so: 我像这样设置POST请求:

    $scope.addUser = function() {
        console.log($.param($scope.user));
        $http({
            method: 'POST',
            url: '/addUser',
            data: $.param($scope.user),
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).
        success( function(response) {
            console.log("success");
        }).
        error( function(response) {
            console.log("error");
        });

    };

The $scope.user variable is { name: "john", email: "doe" } , and evaluates to name=john&email=doe when passed through $.param($scope.user) . $ scope.user变量为{ name: "john", email: "doe" } ,并且通过$.param($scope.user)传递为name=john&email=doe I originally thought the problem was the content-type of the request, which was originally a JSON object. 我本来以为问题是请求的内容类型,它最初是JSON对象。 After reading about similar problems I changed the content-type to x-www-form-urlencoded, but still could not grab the data from the POST request. 在阅读了类似的问题后,我将内容类型更改为x-www-form-urlencoded,但是仍然无法从POST请求中获取数据。

Here is the server-side NodeJS script that is hit with the POST request: 这是通过POST请求命中的服务器端NodeJS脚本:

app.post('/addUser', function(req, res) {
    console.log(req.params);
});

I know the server-side script is being reached, as I can print out data such as req.method, but attempting to print req.params results in just { }. 我知道已经到达服务器端脚本,因为我可以打印出诸如req.method之类的数据,但是尝试打印req.params只会得到{}。

Why are my POST parameters not going through? 为什么我的POST参数没有通过?

Request bodies are not saved to req.params . 请求正文不会保存到req.params You need to add a middleware to parse the request body for you. 您需要添加一个中间件来为您解析请求正文。 req.params is for key=value pairs supplied as part of the URL (eg POSTing to "/foo/bar?baz=bla" would result in req.params.baz === 'bla' ). req.params适用于作为URL一部分提供的key=value对(例如POST到“ / foo / bar?baz = bla”会导致req.params.baz === 'bla' )。

Some example solutions: 一些示例解决方案:

  • body-parser - parses only application/json and application/x-www-form-urlencoded request bodies. body- parser-仅解析application / jsonapplication / x-www-form-urlencoded请求主体。

  • formidable - parses application/json , application/x-www-form-urlencoded , and multipart/form-data . 强大 -解析application / jsonapplication / x-www-form-urlencodedmultipart / form-data This is what was used in the body parser in Express 3. I'm not sure if there is an "official" Express middleware for it for Express 4. 这就是Express 3的主体分析器中使用的工具。我不确定Express 4是否为其使用了“官方” Express中间件。

  • busboy - parses application/x-www-form-urlencoded and multipart/form-data . busboy-解析application / x-www-form-urlencodedmultipart / form-data It does not save files to disk itself, but instead presents files as readable streams. 它不会将文件保存到磁盘本身,而是将文件显示为可读流。 The API differs from formidable(/body parser from Express 3). 该API与强大(Express 3中的/ body解析器)不同。 There are a few Express middleware available for busboy: 有一些Express中间件可用于busboy:

    • connect-busboy - a thin wrapper that merely sets up a Busboy instance on your req . connect-busboy-一个薄包装器,仅在您的req上设置Busboy实例。 You can set it to automatically start parsing the request, or you can pipe the request manually to req.busboy when you want to start. 您可以将其设置为自动开始解析请求,也可以在要启动时手动将请求通过管道传递到req.busboy

    • multer - provides an interface more similar to the Express 3 body parser middleware (with req.body and req.files set). multer-提供与Express 3 body解析器中间件更相似的界面(设置了req.bodyreq.files )。

    • reformed - a new module that provides a layer on top of Busboy to provide mechanisms similar to formidable (eg saving uploaded files to disk) but also other features such as field validation. 改良 -一个新模块,在Busboy之上提供一层,以提供类似于强大的机制(例如,将上传的文件保存到磁盘)以及其他功能,例如字段验证。

Since you are using express.js your POST fields are received as part of the body not the URL so you need use body instead of params : 由于您使用express.js,因此您的POST字段将作为正文的一部分而不是URL接收,因此您需要使用body而不是params

app.post('/addUser', function(req, res) {
    console.log(req.body);//also possible req.body.name | req.body.email
});

How about trying a simpler POST something like this (for testing purposes only ): 如何尝试这样的更简单的POST( 用于测试目的):

  $http.post('/addUser',{ "name": "john", "email": "doe" }).success(function(response) {
           console.log("success");
          }).error(function(err){
             console.log("failure")
          });

Please note that Params are used as URL parameters; 请注意,参数用作URL参数。 something like this: 像这样的东西:

app.get('/addUser/:userID', function(req, res) {
        console.log(req.params.userID);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM