我正在按照教程使用MongooseDB、Express等设置React应用程序。我使用Postman进行GET、POST。参见下面的代码(我已经将数据库字符串中的密码加了星号)。
当我发送GET HTTP://localhost:8001时,它会显示我期望的"hello world“。
当我发送GET HTTP://localhost:8001/tinder/card时,它挂起并最终显示错误" error : socket hang“。
当我发送POST HTTP://localhost:8001/tinder/card时,它挂起并最终给出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}`)); 发布于 2021-09-28 12:22:47
您还应该添加urlencoded中间件:
app.use(express.json());
app.use(express.urlencoded({
extended: true,
}));https://stackoverflow.com/questions/69358810
复制相似问题