my express app serving static react front-end works ok when deployed on heroku. Now I want to develop locally so I don't need to commit and push to see actual changes.
So I need to proxy the fetch from my front-end to my back-end as those run on different ports.
Adding a proxi in the front-end package.json works. But I want to clean it a bit and instead, use http-proxy-middleware
I've been trying to make it work in every manner, read everything about it, but still, I can't make it work.
Here is a simplified version of my index.js file containing my express app.
const express = require('express')
const app = express()
require('dotenv').config()
const path = require('path')
const { createProxyMiddleware } = require('http-proxy-middleware')
const bodyParser = require('body-parser')
const isDev = process.env.STATUS === 'development'
const PORT = isDev ? '5000' : process.env.PORT
const db = require('./db/queries.js')
const router = {
articles: express.Router(),
users: express.Router(),
shoppingLists: express.Router(),
}
app.use(express.static(path.resolve(__dirname, './public/build')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './public/build', 'index.html'))
})
app.use(bodyParser.json())
if (isDev)
{
app.use(
createProxyMiddleware({
target: `http://localhost:${PORT}`,
changeOrigin: true,
})
)
}
app.get('*', (req, res) => {
console.log('Come on, please !')
res.sendStatus(200)
})
app.listen(PORT, (req, res) => {
console.log('Server is listening on port ', +PORT)
})
What I expect is that every request sent from localhost:3000 would then be redirect to localhost:5000 with this line of code
app.use(
createProxyMiddleware({
target: `http://localhost:${PORT}`,
changeOrigin: true,
})
)
Now here is the response I get from my request and see, the url show port 3000 instead of 5000 as I want it to be.
Do you guys see something wrong with my code ? Thank you