浏览器在POST请求上等待localhost

时间:2017-08-28 18:32:44

标签: node.js mongodb express post

我正在建立一个网站,我有一个注册表单,我需要通过POST提交表单,并在mongoDB数据库中注册用户。到目前为止网站工作正常,但是当我提交注册表单时,浏览器只是等待本地主机"永远。我使用EJS作为我的模板引擎,虽然我不认为这很重要。

register.ejs:

<% include partials/header %>
<%include partials/nav %>
<h1>REGISTER</h1>
<a href="/login">Login</a>

 <form  id="registerForm" action="/register" method="post">
            <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
                <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Password</label>
                <input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
                <small id="passwordHelp" class="form-text text-muted">Your password must be at least 8 characters long.</small>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
<% include partials/footer %>

app.js:

var express = require('express'),
    app = express(),
    mongoose = require('mongoose'),
    passport = require("passport"),
    bodyParser = require("body-parser"),
    User = require("./models/user"),
    LocalStrategy = require("passport-local"),
    passportLocalMongoose = require("passport-local-mongoose");

//Set up MongoDB
var mongo = require("mongo");
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/customerapp';
//MongoJS
var mongojs = require("mongojs");
var db = mongojs("customerapp", ["users"]);
//Mongoose
var mongoose = require('mongoose');
mongoose.Promise = global.Promise
mongoose.createConnection("mongodb://localhost:27017/customerapp");
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(require("express-session")({
    secret: "wah wah wah",
    resave: false,
    saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());


var index = require("./routes/index");
var about = require("./routes/about");
var login = require("./routes/login");
//var register = require("./routes/register");

app.all("index", index);
app.all("about", about);
app.all("login", login);
//app.all("register", register);

// AUTH Routes
//Register get request
app.get("/register", function(req, res) {
    res.render("register");
});

//Handle post register req. at '/register'
app.post("/register", function(req, res) {
    User.register(new User({
        username: req.body.username}),
        req.body.password,
        function(err, user) {
            if(err) {
                console.log(err);
                return res.render("register");
            }
            passport.authenticate("local")(req, res, function() {
                res.redirect("/secret")
            })
    });
});
app.listen(process.env.PORT || 3000, process.env.IP, function () {
  console.log('Example app listening on port 3000!')
})

2 个答案:

答案 0 :(得分:1)

你使用三个参数而不是两个,使用它就像这样。

//Handle post register req. at '/register'
app.post("/register", function(req, res) {
    User.register(new User({
        username: req.body.username,
        password: req.body.password
        }),
    function(err, user) {
        if(err) {
            console.log(err);
            return res.render("register");
        }
        passport.authenticate("local")(req, res, function() {
            res.redirect("/secret")
        })
 });
});

答案 1 :(得分:0)

检查并确保您的mongoDB和mongoose版本兼容。您可以找到兼容性图表here

除了检查您的MongoDB和Mongoose版本外,您还应该在连接到服务器时通过使用回调函数检查它是否确实在连接数据库,例如:

//Connecting to database using mongoose.connect with a callback
mongoose.connect("mongodb://localhost:27017/customerapp", function(error) {
  if(error) {
    console.log("There was an error connecting to MongoDB.");
    console.log(error);
  } else {
    console.log("Successfully connected to MongoDB!");
  }
});

此回调也可以使用mongoose.createConnection而不是mongoose.connect,但我没有尝试过。如果这两个消息均未打印到控制台,则表明该应用未从服务器获得任何响应,甚至没有错误。

由于某种原因,只要mongoDB一直在运行,即使连接尝试挂起,GET请求似乎仍然可以工作,但是POST请求会遇到麻烦。

来源:Mongoose never connects to mongodb