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?