【发布时间】:2021-11-20 07:45:39
【问题描述】:
我正在学习使用 MongooseDB、Express 等设置 React 应用程序的教程。我正在使用 Postman 进行 GET、POST。请参见下面的代码(我已为数据库字符串中的密码加注星标)。
当我发送 GET HTTP://localhost:8001 时,它会显示我期望的“hello world”。
当我发送 GET HTTP://localhost:8001/tinder/cards 时,它挂起并最终显示错误“错误:套接字挂起”。
当我发送 POST HTTP://localhost:8001/tinder/cards 时它挂起并最终给出 500 Internal Server 错误。
谁能指出我在哪里调试?我猜想当我发送 GET HTTP://localhost:8001 时,连接会显示“hello world”。
再次感谢。
import express from 'express'
import mongoose from 'mongoose'
import Cards from './dbCards.js'
import Cors from 'cors'
// App Config
const app = express();
const port = process.env.PORT || 8001
const connection_url = `mongodb+srv://admin:*******@cluster0.iyemf.mongodb.net/tinder-db?retryWrites=true&w=majority`
// middlewares
app.use(express.json())
app.use(Cors())
// db config
mongoose.connect(connection_url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology:true,
})
// api endpoints
app.get('/', (req, res) => res.status(200).send("hello world"));
app.post('/tinder/cards', (req, res) => {
const dbCard = req.body;
Cards.create(dbCard, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get("/tinder/cards", (req, res) => {
Cards.find((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
});
});
// listener
app.listen(port, () => console.log(`listening on localehost: ${port}`));
【问题讨论】: