我試圖制作一個非常簡單的 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
uj5u.com熱心網友回復:
在你的路由處理程式中,如果你遇到錯誤,你不會發送任何回應,因此瀏覽器會在那里等待很長時間等待結果回來(最終,它會超時)。除非您向其發送錯誤,否則您的錯誤處理程式不會自動獲取錯誤。
我建議將您的路由處理程式更改為:
booksRoute.route('/').get((req, res, next) => {
BookModel.find((error,data)=>{
if (error) {
next(error);
} else {
res.json(data) ;
}
})
});
uj5u.com熱心網友回復:
解決了:問題出在這行代碼 mongoose.connect('localhost:27017/books',()=>console.log("connected successfully to database !")) ; 那是錯誤的資料庫網址。應該是這個而不是'mongodb://localhost:27017/books'
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343614.html
