I’m building a full stack app with the backend developed in Node/Express and the front end managed by React/Vite. If on the frontend I’m fetching data straight from localhost and no proxy configuration in vite.config.js
everything works as expected:
APP.JSX
import { useState,useEffect } from 'react'
import './App.css'
function App() {
const [message, setMessage] = useState()
useEffect(() => {
fetch('http://localhost:3000')
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
setMessage(data.message);
});
}, []);
return (
<>
<h1>{message}</h1>
</>
)
}
export default App
VITE.CONFIG.JS
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
SERVER – APP.JS
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
But when i define the localhost in the proxy configuration to manage all requests and use absolute path in REACT the only thing i get in the browser is the JSON object on itself so i see printed {message:Hello World'}
and this is not coming from fetching or anything is just the response i have if i connect to the frontend localserver
APP.JSX
import { useState,useEffect } from 'react'
import './App.css'
function App() {
const [message, setMessage] = useState()
useEffect(() => {
fetch('/')
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
setMessage(data.message);
});
}, []);
return (
<>
<h1>{message}</h1>
</>
)
}
export default App
VITE.CONFIG.JS
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server:{
proxy:{
'/': 'http://localhost:3000'
}
}
})
How can i solve this issue?