簡體   English   中英

使用 node.js 從 Mongodb 獲取數據時,瀏覽器會一直加載

[英]browser keeps loading forever when getting data from Mongodb using node.js

我試圖制作一個非常簡單的 MEAN STACK 應用程序,它只從 mongodb 請求中獲取書名、價格,但是當我輸入 url 以獲取數據時,它只會在瀏覽器中永遠加載,這是主要代碼

const express = require("express") ; 
const mongoose = require("mongoose") ;
cors = require('cors') ;
const path = require('path') ;
bodyParser = require('body-parser') ;
const app = express() ; 
const port = 3000 ;
const booksRoute = require('./routes/api') ;

// enable cross-origin sharing and ...
app.use('/api',booksRoute) ;
app.use(cors()) ; 
app.use(express.static(path.join(__dirname,'dist/smart-bookshelf'))) ;
app.use('/',express.static(path.join(__dirname,'dist/smart-bookshelf'))) ;
app.use(bodyParser.json()) ;
app.use(bodyParser.urlencoded({
  extended:false 
})) ;

mongoose.connect('localhost:27017/books',()=>console.log("connected successfully to database !")) ;

const server = app.listen(3000,()=>{console.log("server is working correctly on port : "+port)}) ;

// error handler
app.use(function (err, req, res, next) {
  console.error(err.message); // Log error message in our server's console
  if (!err.statusCode) err.statusCode = 500; // If err has no specified error code, set error code to 'Internal Server Error (500)'
  res.status(err.statusCode).send(err.message); // All HTTP requests must have a response, so let's send back an error with its status code and message
});

這是路線代碼

mongoose = require('mongoose') ;
const express = require('express') ;
const BookModel = require('../models/bookModel');
const booksRoute = express.Router() ;

booksRoute.route('/').get((req,res)=>{
    BookModel.find((error,data)=>{
        if (error){
            console.log("an error accured while retrieving data !") ; 
        }
        else{
            res.json(data) ;
        }
    })
}) ;

module.exports = booksRoute ; 

https://github.com/mohamedalimani/bookshelf

在你的路由處理程序中,如果你遇到錯誤,你不會發送任何響應,因此瀏覽器會在那里等待很長時間等待結果回來(最終,它會超時)。 除非您向其發送錯誤,否則您的錯誤處理程序不會自動獲取錯誤。

我建議將您的路由處理程序更改為:

booksRoute.route('/').get((req, res, next) => {
    BookModel.find((error,data)=>{
        if (error) {
            next(error);
        } else {
            res.json(data) ;
        }
    })
});

解決了:問題出在這行代碼 mongoose.connect('localhost:27017/books',()=>console.log("connected successfully to database !")) ; 那是錯誤的數據庫網址。 應該是這個而不是'mongodb://localhost:27017/books'

暫無
暫無

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

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