【问题标题】:404 (Not Found) when trying to route to the index with mongodb and nodejs尝试使用 mongodb 和 nodejs 路由到索引时出现 404(未找到)
【发布时间】:2017-07-07 02:42:55
【问题描述】:

我正在为一个作为视频游戏伴侣的作品集开发应用程序,但我似乎无法让它连接到 mongo 服务器。

我的代码似乎可以正常工作,因为当我在节点中运行 server.js 时,连接成功,因为这是我的终端所说的。

(node:45137) DeprecationWarning: open() 在 mongoose >= >4.11.0 中已弃用,请改用 openUri(),或者如果 > 使用 connect()createConnection() 则设置 useMongoClient 选项。见http://mongoosejs.com >/docs/connections.html#use-mongo-client 应用程序在端口 27017 上运行! Mongoose 连接成功。

但是当我尝试将它放在本地主机上时它失败了

GET http://localhost:27017/404(未找到)

这是我的服务器代码,其中包含路由。

我已经仔细检查以确保所需的所有样式和 javascript 都已正确链接,但仍然不行。

// Dependencies
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var exphbs = require("express-handlebars");
var request = require("request");

// Set mongoose to leverage built in JavaScript ES6 Promises
mongoose.Promise = Promise;


// Initialize Express
var app = express();

// Use morgan and body parser with our app
app.use(bodyParser.urlencoded({
  extended: false
}));

// Make public a static dir
app.use(express.static(__dirname + "/public"));

app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");

// Database configuration with mongoose
mongoose.connect("mongodb://localhost/usersdb");
var db = mongoose.connection;

// Show any mongoose errors
db.on("error", function(error) {
  console.log("Mongoose Error: ", error);
});

// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
  console.log("Mongoose connection successful.");
});


//routes

app.get('/', function(req, res, next, error){
	// Log any errors
    if (error) {
      console.log(error);
    }
    // Or send the doc to the browser as a json object
    else {
    res.render("index",{ title: 'Express' });
      }
});




// Listen on port 27107
app.listen(process.env.PORT || 27017, function() {
  console.log("App running on port 27017!");
});

有什么想法吗?

【问题讨论】:

    标签: jquery node.js mongodb


    【解决方案1】:

    你为路由器处理程序设置了错误的签名,而不是app.get('/', function(req, res, next, error){,你需要使用app.get('/', function(req, res, next){,没有error参数,如果发生应该放在第一位,当错误参数发生时,这个处理程序将是一个错误中间件。

    【讨论】:

    • 这就是问题所在!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-24
    • 2018-12-25
    • 2017-02-28
    • 1970-01-01
    • 2020-08-23
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多