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

Getting error while connecting node and mongo as cannot GET /

大家好,我正在尝试连接 mongo 和节点。但我越来越不能得到请帮我解决这个问题 我的代码如下。如果有人帮助我解决这个问题,那就太好了 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;

正如 expressjs 4.0 文档中所说:

res.redirect([status,] path)

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code. If not specified, status defaults to “302 “Found”.

这意味着 res.redirect(); 不提供文件;相反,它 redirects/forwards 请求到指定的路径。因此,您必须为 /login 定义一个快速获取路由,如下所示:

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

这是文档

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

这里你只需要在你的root文件中导入路由和定义中间件

在此处提供 index.js file 的路径 我假设您在 routes/index.js

中有 index.js 文件
const routes = require('./routes/index')

并使用像

这样的中间件
app.use('/get', routes);

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