簡體   English   中英

連接節點和 mongo 時出錯,因為無法 GET /

[英]Getting error while connecting node and mongo as cannot GET /

大家好,我正在嘗試連接 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;

正如 expressjs 4.0 文檔中所說:

res.redirect([狀態,] 路徑)

重定向到從指定路徑派生的 URL,具有指定狀態,正 integer 對應於 HTTP 狀態代碼。 如果未指定,狀態默認為“302“找到”。

這意味着res.redirect(); 不提供文件; 相反,它將請求重定向/轉發到指定路徑。 因此,您必須為/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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM