AngularJS未将数据发送到Node Express

时间:2020-04-12 03:10:22

标签: javascript node.js angularjs express http-headers

我正在使用AngularJS,是的,我知道AngularJS已经过时了,应该使用Angular 9,但这是用于学校作业,我真的没有选择。

我的html导航栏中有一个搜索栏,如下所示:

<ul id="nav-mobile" class="right hide-on-med-and-down">
    <li><input ng-model="crypto" type="text" placeholder="Search CryptoDash" style="color: white;"></li>
    <li>
        <a ng-click="search(crypto)" class="btn white waves-effect waves-light">Submit</a>
    </li>
</ul>

在我的client.js文件(我存储了所有AngularJS app.controller处理)中,我有一个$scope函数,称为搜索。我将输入数据从搜索栏转换为JSON Blob,如果我对其进行控制台记录,则以{name: "BTC"}为例。该功能如下:

// Search the database
$scope.search = function(crypto){
    data = {name: crypto};
    $http.get('/search', JSON.stringify(data))
        .then(function (response) {
            console.log("STATUS:", response.status, response.text)
        });
};

现在跳到我的server.js文件,我有了基本搜索功能的框架:

// Search route, makes a request to db
app.get('/search', function(req,res){
    console.log(req.body);
    res.end();
})

服务器端的控制台日志将undefined返回到我的控制台。我不明白为什么。如果仅控制台req进行日志记录,那么就会有大量的日志转储,其中包含有关标题和套接字等的数百行长的记录,而req却是我提交的输入数据。我不知道它去了哪里,但是可以肯定的是,/ search路由被前端打中了,所以问题可能在于我如何构造GET请求。任何帮助,将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

您需要以params的形式发送数据,而无需对其进行字符串化处理:

 $http
 .get('/search', { params: data })
 .then(function (response) {
      console.log("STATUS:", response.status, response.text)
 });