5

I'm trying to make a project using the MERN stack and I encountered this error. I already added the proxy do the JSON file but still no luck.

the error:

GET http://localhost:5000/posts net::ERR_CONNECTION_REFUSED

my actions:

export const getPosts = () => async (dispatch) => {
try {
    const {data} = await api.fetchPosts();

    dispatch({type: 'FETCH_ALL', payload: data});

} catch (error) {
    console.log(error.message);
}

// const action = {type: 'FETCH_ALL', payload: []}

// dispatch(action);
}

export const createPost = (post) => async (dispatch) => {
try {
    const {data} = await api.createPost(post);
    dispatch({type: 'CREATE', payload: data})
} catch (error) {
    console.log(error);        
}
}

my route /posts:

const router = express.Router();

router.get('/', getPosts);
router.post('/', createPost);

export default router;

server controller:

    export const getPosts = async (req, res) => {
        try {
            const postMessages = PostMessage.find();

            console.log(postMessages);

            res.status(200).json(postMessages);
        } catch (error) {
            res.status(404).json({message: error.message});
        }
    }

    export const createPost = async (req, res) => {
        const post = req.body;

        const newPost = new PostMessage(post);
        try {
            await newPost.save();

            res.status(201).json(newPost);

        } catch (error) {
            res.status(409).json({message: error.message});
        }
    }

server index.js:

    const app = express();

    //MIDDLEWARE

    app.use(bodyParser.json({limit: "30mb", extended: true}));
    app.use(bodyParser.urlencoded({limit: "30mb", extended: true}));
    app.use(cors());

    app.use('/posts', postRoutes);

    
    const PORT = process.env.PORT || 5000;

    mongoose.connect(CONNECTION_URL, {useNewUrlParser:true, useUnifiedTopology: true}) 
        .then(()=> app.listen(PORT, () => console.log('Server running on port:', PORT)))
        .catch((error)=> console.log(error.message));

    mongoose.set('useFindAndModify', false);

client api index:

    const url = 'http://localhost:5000/posts';

    export const fetchPosts = () => axios.get(url);
    export const createPost = (newPost) => axios.post(url, newPost)

client.json:

{
  "name": "osteoft",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:5000",
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "axios": "^0.21.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-file-base64": "^1.0.3",
    "react-redux": "^7.2.2",
    "react-scripts": "4.0.1",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "web-vitals": "^0.2.4"
  },

Is there something missing when I tried to configure the connection?

Henrique Guimarães
  • 203
  • 1
  • 3
  • 17
  • 1
    Do you create a server that uses your `app` object and listens to `PORT`? Could you share that part of the code too? – Cem Jan 01 '21 at 21:48
  • 1
    Just like how it is in my index.js of the server. For now at least. But I guess this should be working by now, since I need to test to see if my posts are getting in the database – Henrique Guimarães Jan 01 '21 at 22:02
  • Can you add `const http = require('http'); const server = http.createServer(app); server.listen(PORT);` at the end of your server index.js, and try sending the request again? – Cem Jan 01 '21 at 22:09
  • it tells me that the ´require´ function is not defined :| – Henrique Guimarães Jan 01 '21 at 22:19
  • I just edited my server index.js. It was missing the mongoose connection here which has the app.listen – Henrique Guimarães Jan 01 '21 at 22:48
  • I still think your server can't start for some reason. Can you change the callback given to app.listen, so that it prints any potential error? `app.listen(PORT, (err) => { if (err) console.log(err); else console.log('Server running on port:', PORT); })` Do you get any errors printed? Do you see the `'Server running on port:'` log? – Cem Jan 01 '21 at 23:15
  • Nothing new. Still getting a GET http://localhost:5000/posts 404 (not found). I understand the CONNECTION_REFUSED was because I was forgetting to start up the server, but still not working – Henrique Guimarães Jan 01 '21 at 23:21

8 Answers8

3

I am currently doing the same tutorial and had the same issue. Turned out I forgot to run the backend server, I was only running the front end one.

Blfie
  • 31
  • 4
1

I had the same problem as well. If you are okay with making the database public (albeit access to update will need credentials), you can resolve this quickly by pressing "Allow Access Anywhere". Otherwise you can just add the new ip address or whitelist multiple IP address ranges as seen here: https://studio3t.com/knowledge-base/articles/mongodb-atlas-login-ip-whitelisting/

mwyatt896
  • 11
  • 1
1

I am doing the same tutorial. Memory app?

You need to add

import express from 'express';

to the top of the controllers/posts

KLW
  • 11
  • 1
0

I had the same problem, and I after a LOT of searching a stepping through and watching the tutorial again, I finally noticed that when running '$ npm start' on my server, I would get a message saying the mongodb rejected the connection, and that it is usually because the ip address you are using isn't white-listed.

Go to mongodb.com/cloud/atlas, then to 'Network Access' in the mongodb dashboard, and add a new ip address and there's simply a button to add your ip address.

0

I'm currently doing the same project right now and I have tried every response here so far, but I'm still getting POST http://localhost:5000/posts net::ERR_CONNECTION_REFUSED error

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 25 '23 at 13:40
0

I was getting same other. This was because, I used
app.use(cors); it should have been app.use(cors());

0

i just replace "post" from const newPost = new PostMessage(post) by "body" in const newPost = new PostMessage(body)

0
try {
    await newPost.save();
    res.status(201).json(newPost);
} catch (error) {
    res.status(409).json({
        message: error.message
    });
}

Convert this to:

try {
    await newPostMessage.save();
    res.status(201).json(newPostMessage);
} catch (error) {
    res.status(201).json(newPostMessage);
}
Jan Schultke
  • 17,446
  • 6
  • 47
  • 96