mongodb 无法使用express js连接到路由

jum4pzuy  于 2023-04-20  发布在  Go
关注(0)|答案(2)|浏览(128)

尝试通过Route连接API没有响应,获取状态错误:“未连接”

restaurants.route.jsIntegrated The Route Here

import express from "express"
const router = express.Router()
router.route('/api/v1/restaurants').get((req,res) => res.send("helloworld"))
export default router

index.js连接MongoDB。

import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config()
const MongoClient = mongodb.MongoClient

const port = process.env.PORT || 8000

MongoClient.connect(
    process.env.RESTREVIEWS_DB_URI,
    {
        maxPoolSize: 50,
        wtimeoutMS: 2500,
        useNewUrlParser: true,
    }
)
.catch(err =>{
    console.error(err.stack)
    process.exit(1)
})
.then(async client =>{
    App.listen(port,() =>{
        console.log(`listen on port ${port}`)
    })
})

server.js连接服务器

import  express  from "express";
import cors from "cors";
import restaurants from "./api/restaurants.route.js"

const App = express()

App.use(cors())
App.use(express.json())

App.use("/api/v1/restaurants", restaurants)
App.use("*", (req, res) => res.status(404).json({error:"not connected"}))

export default App
holgip5t

holgip5t1#

您应该将路由中间件声明为:

App.use("/", restaurants)

否则,将端点初始化为/api/v1/restaurants/api/v1/restaurants

bnl4lu3b

bnl4lu3b2#

App.use("/api/v1/restaurants", restaurants)更改为App.use("/api/v1", restaurants),将router.route('/api/v1/restaurants')更改为router.route('/')

相关问题