首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将Postman与ReactJS和MongooseDB一起使用时显示" error : socket hang“错误

将Postman与ReactJS和MongooseDB一起使用时显示" error : socket hang“错误
EN

Stack Overflow用户
提问于 2021-09-28 09:07:20
回答 1查看 261关注 0票数 0

我正在按照教程使用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“。

再次感谢。

代码语言:javascript
复制
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}`)); 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-28 12:22:47

您还应该添加urlencoded中间件:

代码语言:javascript
复制
app.use(express.json());
app.use(express.urlencoded({
    extended: true,
}));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69358810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档