连接节点和mongo时出错,因为无法获取/

问题描述 投票:0回答:2

[大家好,我正在尝试连接mongo和node。但我不能得到请帮助我我的代码如下。如果有人帮助我解决这个问题,那就太好了app.js

var express = require("express");
var bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/NammaDB');
var db = mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));

db.once('open', function(callback) {
    console.log("connection succeeded");
})
var app = express()
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.post('login', function(req, res) {
    var name = req.body.username;
    var pass = req.body.password;
    var data = {
        "eid": hello,
        "pwd": hello,
    } 
    db.collection('users').insertOne(data, function(err, collection) {
        if (err) throw err;
        console.log("Record inserted Successfully");

    });

    return res.redirect('/login.html');
})


app.get('/', function(req, res) {
    res.set({
        'Access-control-Allow-Origin': '*'
    });
    return res.redirect('login.html');
}).listen(3000)
console.log("server listening at port 3000");

我的index.js代码如下index.js

const express = require('express');

const router = express.Router();

router.get('/', (req, res) => {
  res.send('It works!');
});

module.exports = router;
node.js mongodb express mongoose node-mongodb-native
2个回答
0
投票

正如expressjs 4.0文档中所说:

res.redirect([status,] path)

重定向到从指定路径派生的URL,具有指定状态,为肯定对应于HTTP状态代码的整数。如果未指定,则状态默认为“ 302“找到”。

这意味着res.redirect();不提供文件;而是将请求重定向/转发到指定的路径。因此,您必须为/login定义快速获取路线,如下所示:

app.get("/login", (req, res) => {
  //whatever you need to do
});

这里是文档

https://expressjs.com/en/4x/api.html#res.redirect


0
投票

这里您只需要导入路由并在root文件中定义中间件

在这里给定index.js file的路径,假设您在index.js中有routes/index.js文件

const routes = require('./routes/index')

并且使用中间件,例如

app.use('/get', routes);

现在您的URL看起来像http://localhost:3000/get

© www.soinside.com 2019 - 2024. All rights reserved.