I have a simple application in react.js + vite. I have the api set up on “http://localhost:5000”, and the vite app on “http://localhost:5173”.
The proxy in vite is ignored and I don’t know how to fix it.
vite.config.js:
export default defineConfig({
plugins: [react()],
// mode: Config.WEBSITE.FRONTEND.production ? 'production' : 'development',
server: {
server: {
proxy: {
'/api': {
target: 'http://localhost:5000/',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^/api/, "")
}
}
}
}
})
app.js (api):
app.use(cors(cors: { - use to no have problem with cors on react.js side
origin: `http://localhost:5173`,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
optionsSuccessStatus: 200, // dla starszych przeglądarek
credentials: true
}));
app.use((req, res, next) => {
const customHeader = req.headers['x-auth-token'];
if (customHeader !== "test") {
return res.status(403).send('Forbidden');
}
next();
});
app.get('/', (req, res) => {
res.json({ text: "API WORK" });
});
Home.jsx (home page react element with api request in axios):
useEffect(() => {
axios.get('/api', {
headers: {
"Content-Type": "application/json",
'x-auth-token': 'test'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
}, []);
When it executes the request, the proxy does not redirect to the api address, and the zwrtony response in the request I have is like this:
website console log
When I use in axios url “http://localhost:5000/” instead of “/api”, everything works normally and retrieves the get request from the api. So why is the proxy not working?
Thank you for any help.
I tried changing ports, vite.config.js of course nothing helped. I searched the whole internet about vite proxy problem and so far I am not sure what is problem.
darek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.