无法在MEAN单页面应用程序中发布

时间:2014-12-18 04:51:54

标签: javascript angularjs node.js express mean-stack

我刚刚开始尝试NodeJS。对Angular有一点经验,我想过尝试scotch的MEAN堆栈待办事项应用教程。

我理解发生了什么以及角度,节点和我的视图应该如何协同工作。但他们并不是。我确保不要错过任何东西。这是我的代码。

Server.js位于根文件夹

// server.js

// set up ========================
var express  = require('express');
var app      = express();                               // create our app w/ express
var mongoose = require('mongoose');                     // mongoose for mongodb
var mongodb = require('mongodb');
var morgan = require('morgan');             // log requests to the console (express4)
var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)

// configuration =================

mongoose.connect('mongodb://<user>:<pass>@proximus.modulusmongo.net:27017/uwa8sIje');     // connect to mongoDB database on modulus.io

app.use(express.static(__dirname +'/public'));                 // set the static files location /public/img will be /img for users
app.use(morgan('dev'));                                         // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());

// creating mongoose model ================================

var Todo = mongoose.model('Todo', {
    text: String
});

// Todo is the mongo db. Creating API for CRUD in the db
//============================================================


app.get('/api/todos', function(req, res) {

    Todo.find(function (err, todos) {       //within 'get' we are looking for all the entries in the db 
        if(err) {
            res.send(err)                   //checking for errors
        }
        res.json(todos);                    //response sends all listed todos in JSON 
    })
})

app.post('/api/todos', function(req, res) { //to post a new todo

    Todo.create({                           //creating a new post. information comes from AJAX request from Angular
        text: req.body.text,
        done: false
    }, function(err, todo) {                //checking errors
        if(err) {
            res.send(err);
        }

        Todo.find(function (err, todos) {   //after post is added, find and display all existing todos again
            if(err) {
                res.send(err)
            }
            res.json(todos);
        })

    })

})

app.delete('/api/todos/:todo_id', function(req, res) {  //delete a todo

    Todo.remove({                                       //remove a todo from database
        _id: req.params.todo_id,                        //todo id to be removed is provided by the request url(params)
    }, function(err, todo) {
        if(err) {
            res.send(err);
        }


        Todo.find(function (err, todos) {
         if (err) {
            res.send(err)
            }
            res.json(todos);
        })
    })
})

//======================================================================



app.get('*', function(req,res) {
    res.sendfile('./public/index.html')                 //load this single view file. angular will handle the 
                                                        //page changes on the front end
})


// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");

我的角度控制器与我的视图一起位于公共文件夹中

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

function mainController($http, $scope) {

    $scope.formData = {};

    $http.get('/api/todos')
        .success(function (data) {
            $scope.todos = data;
            console.log(data);
        })

    $scope.createTodo = function() {

        $http.post('/api/todos', $scope.formData)
            .success(function (data) {
                $scope.formData = {};
                $scope.todos = data;
            })
            .error(function (data) {
                console.log('Error' + data)
            })
    }

    $scope.deleteTodo = function(id) {

        $http.delete('/api/todos/' + id)
            .success(function (data) {
                $scope.todos = data;
                console.log(data);
            })
            .error(function (data) {
                console.log(data)
            });
    };

Todoz.controller("mainController", mainController);

}

和我的最小视图

<head>
    <title>
        To-Do-and-Node-To-Do
    </title>
</head>
<body ng-app="Todoz">

<h1>The To-do-ist</h1>

<div ng-controller="mainController">
    <div>
        <input type="text" ng-model="formData.text"></input>
        <button type="submit" ng-click="createTodo()">Submit</button>
    </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="./core.js"></script>
</body>

当我使用&nodedom server.js&#39;启动服务器时我的控制台记录了一个/ GET请求,应用程序显示在我的端口8080上。但是当我尝试从我的文本框中发布一个新项目并期望它到console.log时,它没有做任何事情。我的浏览器控制台返回此

POST http://localhost:8080/api/todos net::ERR_CONNECTION_REFUSED        angular.js:8632
Error core.js:23
POST http://localhost:8080/api/todos net::ERR_CONNECTION_REFUSED        angular.js:8632
Error core.js:23

请帮忙。我不知道出了什么问题。

0 个答案:

没有答案