首页 > 解决方案 > 尝试从节点服务器检索 json 对象时获取“Cannot GET /”

问题描述

我正在编写一个 RESTful API。IT 使用 express.js 框架在 node.js 上运行,mongodb 使用 mongoose 作为对象建模工具和 body-parser 来传递 http. 每次我启动服务器并导航到指定的 IP 地址时,都会收到“CANNOT GET/”错误。我怎么能解决这个问题?一些建议将不胜感激。

我已经厌倦了使用不同的端口号,但问题仍然存在。这是我的 server.js 代码的副本:

var express = require('express'),
app = express(),
IP = process.env.IP,
port = process.env.PORT || 8080 ,
mongoose = require('mongoose'),
tasks = require('./api/models/todosModel'),
bodyParser = require('body-parser');

//handiling of promise 
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Todosdb',{ useNewUrlParser: true });

app.use(bodyParser.urlencoded({extended:true})); // telling the sever instance to use body parser
app.use(bodyParser.json()); 

var Routes = require('./api/routes/todoRoutes');
//passing the server instance to the routes 
Routes(app);

app.listen(port,IP);
console.log("The TODO API server is running on IP: " + IP + " and port: " + port);

todoRoute 代码:

'use strict';
module.exports = function(app){
    var todofunctions = require('../controllers/todoController');

    // todo routes
    app.route('/tasks')      //task [GET (all the tasks),POST]
        .get(todofunctions.listTasks)
        .post(todofunctions.createTask);

    app.route('/tasks/:taskId')  //a task [GET(single task),PUT,DELETE]
        .put(todofunctions.updatetask)
        .get(todofunctions.readTask)
        .delete(todofunctions.deleteTask);

};

标签: javascriptnode.jsmongodbexpress

解决方案


这可能是因为您没有为/.

尝试/tasks在浏览器中转到,然后您会得到一些响应。


推荐阅读