0
votes

I am trying to connect my react frontend to the backend i tried everything but its still not working. I added "proxy" : "localhost:5000" and no luck. I tried

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:5000',
            changeOrigin: true,
        })
    );
};

and also no luck. Has anyone found a solution to the problem. I looked all over stackoverflow

UPDATE : Index file

// Imports 
const express = require('express')
const app = express();
const cors = require('cors')
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const config = require('./config/key')
const routes = require('./routes/api')
require('dotenv').config()
// -----Connect to the database
mongoose.connect(config.mongoURI,
    {useNewUrlParser: true,useUnifiedTopology:true,
    createIndexes : true}).then(()=>{
    console.log("Database connected")
}).catch((error)=>{
    console.log(error)
})

// ----setting up middleware 
const corsOptions = {
    origin:['http://localhost:3000'],
    credentials: true,
    optionsSuccessStatus: 200
}
app.use(cors(corsOptions))
app.use(bodyParser.urlencoded({extended : true}))
app.use(bodyParser.json())
app.use(cookieParser())
app.use('/api', routes);


// ---- Setting up server to listen on port 5000
app.listen(5000,()=>{
    console.log("App is running on 5000")
})
2
Can you share the index for the api that runs on port 5000? - onuriltan
@onuriltan what do u mean by the index? its not letting me put the whole file in here so i will update my post. - Adil Khan
try removing changeOrigin from createProxyMiddleware or give corsOptions origin as string - onuriltan
@onuriltan i am getting this now Response {type: "basic", url: "http://localhost:3000/movies/api/favorites", redirected: false, status: 500, ok: false, …} - Adil Khan

2 Answers

0
votes

Update your code to this

const { createProxyMiddleware } = require("http-proxy-middleware");

module.exports = function (app) {
 
  app.use(
    createProxyMiddleware("/api/*", { target: "http://localhost:5000/" })
  );
};
0
votes

The problem for me was the port. It was set to 5432, after changing to 3002 worked again. Don't know why though, because if the port was already being used node should throw an error.