$scope.edit не работает должным образом в controller.js использование MongoDB

#javascript #angularjs #mongodb

#javascript #angularjs #mongodb

Вопрос:

Я новичок в MongoDB (и кодировании в целом), и я пытался создать простое приложение для списка контактов, но столкнулся с проблемой. Я не могу заставить свою кнопку редактирования работать. В частности, это $scope.edit в controller.js похоже, это не работает. Я пробовал два разных способа:

Вот server.js:

 app.get('contactList/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    db.contactList.findOne({_id: mongojs.ObjectId(id)}, function(err, doc) {
        res.json(doc);
    });
})
  

Вот controller.js (1-й способ):

 $scope.edit = function(id) {
    // Displays the user ID in the browser console
    console.log(id);
    $http.get('/contactList/'   id).success(function(response) {
        $scope.contact = response;
    });
}
  

В моем браузере я получаю эту ошибку:

 [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (57fa05975770e4ae924269ba, line 0)
  

Я попытался изменить controller.js к этому (2-й способ):

 $http.get('/contactList/'   id).then(success, fail);
function success(response) {
    console.log("Success!");
}

function fail(err) {
    console.log(err.message);
}
  

И я получаю это сообщение об ошибке:

 [Error] Failed to load resource: the server responded with a status of 404 (Not Found) (57fa05975770e4ae924269ba, line 0)
[Log] undefined (controller.js, line 53)
  

Вот мой полный index.html файл:

 <!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>Contact List App</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>
<body>

    <div class="container" ng-controller="AppCtrl">
        <h1 align="center">Contact List Header</h1>

        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Number</th>
                    <th>Action</th>
                    <th>amp;nbsp;</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <input class="form-control" ng-model="contact.name" type="" name="">
                    </td>
                    <td>
                        <input class="form-control" ng-model="contact.email" type="" name="">
                    </td>
                    <td>
                        <input class="form-control" ng-model="contact.number" type="" name="">
                    </td>
                    <td>
                        <button class="btn btn-primary" ng-click="addContact()">Add Contact</button>
                    </td>
                    <td>
                        <button class="btn btn-info" ng-click="update()">Update</button>
                    </td>
                </tr>
                <tr ng-repeat="contact in contactList">
                    <td>{{contact.name}}</td>
                    <td><a href="mailto:{{contact.email}}">{{contact.email}}</a></td>
                    <td><a href="tel:{{contact.number}}">{{contact.number}}</a></td>
                    <td>
                        <button class="btn btn-danger" ng-click="remove(contact._id)">Remove</button>
                    </td>
                    <td>
                        <button class="btn btn-warning" ng-click="edit(contact._id)">Edit</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<script type="text/javascript" src="controllers/controller.js"></script>
</body>
</html>
  

Мой полный controller.js файл:

 var myApp = angular.module('myApp', []);

myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {   
    var refresh = function() {
        $http.get('/contactList').then(success, fail);

        function success(response) {
            console.log("I got the data I requested");
            $scope.contactList = response.data;
            $scope.contact   "";
        }

        function fail(err) {
            console.log(err.message);
        }
    }

    refresh();

    $scope.addContact = function() {
        // This adds the contact info to the console in the browser
        console.log($scope.contact);

        // This posts the contact info to the server, which can be viewed in terminal
        $http.post('/contactList', $scope.contact).success(function(response) {
            console.log(response);
            refresh();
        });
    }

    $scope.remove = function(id) {
        console.log(id);
        $http.delete('/contactList/'   id).success(function(response) {
            refresh();
        })
    }

    $scope.edit = function(id) {
        // Displays the user ID in the browser console
        console.log(id);
        // $http.get('/contactList/'   id).success(function(response) {
        //  $scope.contact = response;
        // });

        $http.get('/contactList/'   id).then(success, fail);
        function success(response) {
            console.log("Success!");
        }

        function fail(err) {
            console.log(err.message);
        }
    }

    // $scope.update = function() {
    //  console.log($scope.contact._id);
    //  $http.put('/contactList/'   $scope.contact._id, $scope.contact)
    // }
}]);
  

И мой полный server.js файл:

 var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('contactList', ['contactList']);
var bodyParser = require('body-parser');

app.use(express.static(__dirname   "/public"));
app.use(bodyParser.json());

app.get('/contactList', function (req, res) {
    console.log("I got a GET request");

    db.contactList.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });
})

app.post('/contactList', function (req, res) {
    console.log(req.body);
    db.contactList.insert(req.body, function(err, doc) {
        res.json(doc);
    })
});

app.delete('/contactList/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    db.contactList.remove({_id: mongojs.ObjectId(id)}, function(err, doc) {
        res.json(doc);
    });
})

app.get('contactList/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    db.contactList.findOne({_id: mongojs.ObjectId(id)}, function(err, doc) {
        res.json(doc);
    });
})

app.listen(3000);
console.log("Server running on port 3000");
  

Когда я нажимаю на кнопку редактирования, я должен иметь возможность редактировать контакт, но он этого не делает. Может кто-нибудь помочь?

Ответ №1:

В server.js , попробуйте добавить косую черту («/») перед «ContactList /:id» и убедитесь, что server.js бежит. Кроме того, убедитесь, что вы используете mongod в отдельном терминале.

Комментарии:

1. Это сработало! Мне просто не хватало дополнительной косой черты. Какое простое решение. Спасибо! 🙂

2. Приятно :). Не стесняйтесь указывать ответ как «принятый», если у вас все готово!

3. Выполнено. Я пытался поддержать ваш ответ, но, по-видимому, я слишком новичок на этом сайте. В любом случае, я ценю вашу помощь!