javascript - 无法读取 Node js中传入请求的数据

标签 javascript node.js angularjs express

我正在尝试使用 Node、Express 和 AngularJS 创建一个示例登录页面。

下面是我的登录 View

<div class="loginpage">
<div class="loginpage_content">
    <div style="margin-top:30px;padding:10px;width:100%;text-align:center;font-size:20px;font-weight:bold">Please Enter Your Login Crendtials</div>
    <table width="80%" style="margin-top:40px;margin-left:50px;text-align:center;font-size:20px">
        <tr height="40px"><td width="25%">UserName</td><td width="5%">:</td><td width="70%"><input type="text" ng-model="name"></td></tr>
        <tr height="20px"></tr>                     
        <tr height="40px"><td width="25%">Password</td><td width="5%">:</td><td width="70%"><input type="password" ng-model="pass"></td></tr>
        <tr height="30px"></tr> 
        <tr height="40px"><td  colspan="3" style="align:left"><input type="button" value="Login" ng-click="login()"><input type="button" value="Clear" style="margin-left:10px"><a href="" style="margin-left:10px">Change Password</a></td></tr>   
    </table>
    <div style="margin-top:10px;padding:10px;width:99%;text-align:center;font-size:20px;Color:red;display:none">Enter valid Username & Password</div>   
</div>

登录页面 Controller

angular.module("Fms").controller('LoginCtrl',['$scope','$http',function($scope,$http)
{
$scope.results ="";
$scope.name ="";
$scope.pass ="";
$scope.login=function()
{
    $http(
    {   
        method: 'get',
        url: '/login',
        data:  'LOG CHECK',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    }).
    success(function(response) 
    {
        console.log("success"); // Getting Success Response in Callback
        console.log(response);
    }).
    error(function(response) 
    {

    });
}
  }]);

用于处理传入请求的代码

  server.get('/login', function(req, res)
  {
         console.log(req.data);
        res.send("received");
  });

问题是我想读取通过 get 请求传递的数据。我尝试了很多东西...

console.log(req.data);返回未定义为什么???

最佳答案

您的代码中有两个问题。

1) Angularjs $http get 将字段作为 params 来发送请求数据。并且 params 值应该是一个对象。

因此发送请求如下

$http(
{   
    method: 'get',
    url: '/login',
    params:  {data:'LOG CHECK'},
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})

2) 在服务器端读取获取数据,如 req.query.data 而不是 req.data

关于javascript - 无法读取 Node js中传入请求的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25375553/

相关文章:

javascript - 匿名函数参数及其传递顺序

mysql - Sequelize 在收到 SequelizeDatabaseError : ER_LOCK_DEADLOCK 后正在创建悬空/挂起的 mysql 连接

javascript - 使用 Angular 发布表单数据的干净方法?

javascript - ngInfiniteScroll 不工作

javascript - 使用 jQuery 删除浏览器历史记录

Javascript - 递归循环,同时跟踪父子关系

javascript - 我应该使用 `.toPrecision()` 而不是舍入和求幂吗?

javascript - NodeJS + MongoDB 异步结果出现较晚

javascript - Jasmine Node 测试子进程回调

javascript - 使用 sailsjs 的 Angular 路线