Home > other >  "Error: socket hang up" error displayed when using Postman with ReactJS and MongooseDB
"Error: socket hang up" error displayed when using Postman with ReactJS and MongooseDB

Time:09-30

I'm following a tutorial for setting up a React application with MongooseDB, Express etc. I'm using Postman for GET, POST. See code below (I've starred the password from the database string).

When I send GET HTTP://localhost:8001 it shows "hello world" which I expect.

When I send GET HTTP://localhost:8001/tinder/cards it hangs and eventually displays the error "Error: socket hang up".

When I send POST HTTP://localhost:8001/tinder/cards it hangs and eventually gives a 500 Internal Server error.

Can anyone point me in the direction of where to debug please? I'm guessing the connection works as when I send GET HTTP://localhost:8001 it shows "hello world".

Thanks again.

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}`)); 

CodePudding user response:

You should also add the urlencoded middleware:

app.use(express.json());
app.use(express.urlencoded({
    extended: true,
}));
  • Related