简体   繁体   中英

AngularJS not sending data to Node Express

I'm using AngularJS, yes I know AngularJS is outdated and I should be using Angular 9, but this is for a school assignment and I don't really have a choice.

I have a search bar in my html navbar that looks like the following:

<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>

In my client.js file, where I store all of the AngularJS app.controller processing, I have a $scope function called search. I transform the input data from the search bar to a JSON blob, and if I console log it, I get {name: "BTC"} for an example. The function is below:

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

Now hopping over to my server.js file, I have the skeleton of a basic searching function:

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

The console log on the server side returns undefined to my console. I don't understand why. If I console log just req I have a massive log dump hundreds of lines long about headers and sockets etc etc etc, and nowhere req is my submitted input data. I don't know where it went, but one thing is for sure, the /search route is being hit by the front end, so the issue probably lies with how I'm structuring my GET request. Any help would be appreciated. Thanks.

You need to send data as params and no need to stringify it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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