I’m working on building my first website, and it is a very simple project. I’m getting an error when I try to submit a POST or DELETE request using reacjs/axios.
I have all my ports in package.json (in the proxy url) and server.js set to 5000, put the error says localhost:3000 not found.
I had tested in Postman before tried to connect the backend to the frontend, and everything worked. Now, only GET works.
I apologize if this is poorly worded.
Any help would be greatly appreciated. I have been dealing with this issue for days.
My actions folder:
import {GET_RECIPES, ADD_RECIPE, DELETE_RECIPE, EDIT_RECIPE, RECIPES_LOADING} from './types';
import axios from 'axios';
export const getRecipes = () => dispatch =>{
dispatch(setRecipesLoading());
axios
.get('/api/recipes')
.then(res =>
dispatch({
type: GET_RECIPES,
payload:res.data
}))
};
export const deleteRecipe = (_id) => dispatch=>{
axios.delete(`/recipes/${_id}`)
.then(res => dispatch({
type:DELETE_RECIPE,
payload: _id
}))
};
export const addRecipe = (recipe) => dispatch =>{
axios.post('/api/recipes', recipe)
.then(res=>
dispatch({
type: ADD_RECIPE,
payload:res.data
})
);
};
//server.js
const express =require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const recipes = require('./routes/api/recipes');
var cors = require('cors');
app.use(cors())
app.use(bodyParser.json());
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
//db config
const db = require('./config/keys').mongoURI;
//connect to mongo
mongoose.connect(db,
{ useUnifiedTopology: true ,
useNewUrlParser: true})
.then(() => console.log('MONGODB connected'))
.catch(err=> console.log(err));
//Use Routes
app.use('/api/recipes', recipes);
const port = process.env.PORT || 4000;
app.listen(port, () =>console.log(`server started on port ${port}`));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});