node.js - 无法让用户使用 node 和 mongodb 的 restful API

标签 node.js mongodb crud

当我在 server.js 中为用户设置路由并使用 postman/localhost 进行测试时,我收到错误消息,无法获取/users。与任何其他 crud 操作相同。我该如何解决这条路线?

服务器.js

    var express     =   require("express");
    var app         =   express();
    var bodyParser  =   require("body-parser");
    var router      =   express.Router();
    var mongoOp     =   require("./models/mongo");

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({"extended" : false}));

    router.get("/",function(req,res){
       res.json({"error" : false,"message" : "Hello World"});
    });

    router.route("/users")
        .get(function(req,res){
    var response = {};
    mongoOp.find({},function(err,data){
    // Mongo command to fetch all data from collection.
        if(err) {
            response = {"error" : true,"message" : "Error fetching data"};
        } else {
            response = {"error" : false,"message" : data};
        }
        res.json(response);
    });
});

    app.use('/',router);

    app.listen(3000);
    console.log("Listening to PORT 3000");

蒙戈

    var mongoose    =   require("mongoose");
    mongoose.connect('mongodb://localhost:27017/meanapi');

    var mongoSchema =   mongoose.Schema;

    var userSchema = {
        "userEmail" : String,
        "userPassword" : String
     };

     module.exports = mongoose.model('userLogin', userSchema);

最佳答案

对这些情况有帮助的是将 NODE_ENV=development 设置为环境变量并使用 morgan .它打印出所有到达您的 nodejs 服务器的请求,包括状态代码、方法、路径等。

这里有一个简单的设置方法:

if ('production' != app.get('env')) {
    app.use(morgan('dev'));
}

另一个有助于调试的东西是

app.on('error', function (err) {
    console.error(err); // or whatever logger you want to use
});

Ass that after all the middleware and it should print out if some requests fail to get all the way to your handlers.

希望这对您有所帮助!

关于node.js - 无法让用户使用 node 和 mongodb 的 restful API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33223490/

相关文章:

python - 哈希算法 Node js vs Python

ruby - `require ' CoffeeScript 时无法使用 Ctrl+C 停止 Sinatra'`

java - 我的 RESTful API 与 Node/Express 的字符编码错误

javascript - 为用例组合数组

javascript - 如何创建一个基于数组中存储的用户 ID 的简单“点赞”按钮?

MongoDB:如何查询字段为空或未设置的记录?

php - 更新查询不起作用

node.js - mongodb日期范围问题

angular - 无法读取未定义的 CRUD 操作的类型 '_id ' 的属性

string - Grails ID(主键)列作为字符串