I am trying to create a axios post request to my express backend from my react front end
i have tried including the proxy syntax to my package json so it can interact to it and i have also tried React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED)
Here is my client package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:5000",
And here is my api request
axios
.post('api/users/register', newUser)
.then(res => console.log(res.data))
.catch(err => this.setState({ errors: err.response.data }));
here is my express back end, Note i have a api folder that handles each api
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const users = require('./routes/api/users');
const posts = require('./routes/api/posts');
const movies = require('./routes/api/movies');
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Connect to MongoDB
mongoose
.connect("<my mongo db>", { useNewUrlParser: true })
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport Config
require('./config/passport')(passport);
// Use Routes
app.use('/api/users', users);
app.use('/api/posts', posts);
app.use('/api/movies', movies);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
But my react app is running on port 3000
I expect it to output a success message in console, but here is what i got
POST http://localhost:3000/api/users/register 404 (Not Found) xhr.js:166
which shows it is not communicating with my package json proxy.
I think the problem might probably come from the jsx value of the form that is been submit to the express api route. Try the following solution, one of them might make it work
This should solve the issue.