【问题标题】:Cannot pass request from html/angular to node with express无法使用 express 将请求从 html/angular 传递到节点
【发布时间】:2018-02-15 03:54:55
【问题描述】:

我正在尝试在使用 express 单击按钮时将数据从模态表单发送到节点,但我不断收到 req.body 的空白 {}。我试过 .get、.post 和 .all。我在这里发现了很多类似的错误,但它们都处理 body-parser 问题,这似乎不是我的问题。

HTML代码:

    <html lang="en" ng-app="ValidationApp">
    <div ng-controller="Test1" class="container-fluid" style="position:absolute;">

    <button type="button" class="btn-primary" id="get_input"  data-toggle="modal" data-target="#POBI_modal"><i class="fa fa-cloud-download"></i>  Get POBI Data</button><br> 

  <div id="POBI_modal" class="modal fade" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header" style="background-color:rgba(147, 147, 147, .5);">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title style1" style="font-size:24px;">Please enter your Oracle Log-in Information</h4>
                </div>
                <div class="modal-body" >

                    <form class="form-group" name="POBI_form" id="POBI_form"  method="get" action="/input">
                        <div class="form-group row">

                            <label style="margin-left:20px;"class="style1"> Version:
                                <select ng-model="working_final" name="working_final" class="form-control" required>
                                    <option disabled selected value> -- select an option -- </option>
                                    <option value="working">Working</option>
                                    <option value="final">Final</option>
                                </select>
                            </label>
                        </div>

                        <div class="form-group row">
                            <div class="col-lg-5">
                                <input class="form-control" type="text" placeholder="POBI Username" ng-model="username" name="username"
                                       maxlength="6" minlength="6" style="margin-left:5px;" required>
                            </div>
                            <div class="col-lg-5">
                                <input class="form-control" type="password" placeholder="POBI Password" ng-model="pwd" name="pwd" required>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary" onclick="runfile('input','POBI_form')" style="margin-left:5px;" data-dismiss="modal"
                                ng-disabled="POBI_form.$invalid">Enter information</button>
                        <button type="button" class="btn btn-danger" data-dismiss="modal">Exit</button>
                    </form>
                </div>
            </div>

        </div>
     </div>
    </div>
    </html>

角度代码:

<script>
    //when modal is exited wo running, clears all fields

    $(".modal").on("hidden.bs.modal", function(){
        $(".modal-body input").val("")
        $(".modal-body select").val("")
    });


    ////////////////////////////////////////
    var app=angular.module('ValidationApp',[]);
        app.controller('Test1', function($scope,$http){

            $scope.testtext='';

            runfile=function(location1,form_name) {
                $scope.$apply(function (){
                    $scope.location1 = location1;

                     var myForm=$scope[form_name]
                    var data={}
                    angular.forEach(myForm,function(value,key){
                        if(value.hasOwnProperty('$modelValue') && typeof value==='object') {
                            data[key]=value.$modelValue
                        }
                    })
                    console.log(data)

                    $scope.Date1=new Date();

                    $http.post('/'+location1,"message=sdfsdfsd",{headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}})
                            .success(function (data, status, headers, config) {
                                alert('Success')
                            })
                            .error(function (data, status, header, config) {
                                alert('Error')
                            });


/*                        $http.get('/'+location1)
                            .success(function (data, status, headers, config) {
                                if($scope.message1==null){
                                    $scope.message1=headers
                                } else {
                                    $scope.message1=$scope.message1+=data.message1;
                                }

                            })
                            .error(function (data, status, header, config) {
                                alert('Error')
                            });*/

                });
            };
    });
</script>

节点代码:

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

var app=express()
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var server = app.listen(5439, function() {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port);
});
app.post('/input', function(req, res) {
    console.log(req.body)
});

app.get('/',function(req,res){
   res.sendFile('html filename');
});

【问题讨论】:

  • 添加角码。
  • 刚刚添加,谢谢!
  • 从我得到 404 的控制台请求信息:Request Headers:Host: localhost:5439 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0 Accept: application/json, text/plain, */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate X-Requested-With: XMLHttpRequest Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: localhost:5439 Content-Length: 16 Connection: keep-alive Request Body: message=sdfsdfsd

标签: jquery html angularjs node.js express


【解决方案1】:

问题是我试图 GET 和 POST 到同一个 url - 使用 app.all 修复它并使用 if-elsereq.method 分隔 GET 和 POST 代码:

app.all('*',function(req,res){
    if (req.method=='POST') {
       //POST code here
    } else if (req.method=='GET') {
        //GET code here
     }
})

【讨论】:

    【解决方案2】:

    您未在请求中传递数据。您可以执行以下操作:

    $http.post('/input', data)
        .success(function (data, status, headers, config) {
            alert('good');
            alert(data)
            // $scope.message1=data.message1;
        }).error(function (data, status, header, config) {
            alert('bad')
            alert(data)
    });
    

    在你的服务器端,你可以像这样得到它们:

    app.post('/input', function(req, res) {
        console.log(req.body)
        res.json();
    });
    

    Documentation

    【讨论】:

    • 我更新了 angular、node 和 html 表单代码以使用 post。我现在从角度代码中收到一条成功消息,但仍然从节点中的 req.body 中获得空白括号。
    • 在将数据传递到$http.post 之前在控制台打印数据。有没有价值?
    • 是:对象 { working_final: "working",用户名:"thtghf",密码:"fghfghfg" } POST XHR localhost:5439/input
    • 在服务器上打印req的内容。它显示了什么?
    • 太长不能在这里发帖所以:txt.do/d6ba7。第一行是req.url,我可以访问它。我在尝试发布时遇到 404 错误 - 自 GET 以来非常混乱请求成功。
    猜你喜欢
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2020-04-25
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多