I have a react js app initialized with vite and I want to add a Node.js backend, however I can’t, and when I add the index.js and run the command it only initializes the react and doesn’t recognize posts and express routes. Can anybody help me? This is my App.jsx and my index.js:
App.jsx (it is initialized by main.jsx, but it is just vite code):
import { ResolutionList } from "./components/resolutions/ResolutionList";
import { ResolutionForm } from "./components/resolutions/ResolutionForm";
import {BrowserRouter as Router,Route, Routes as Switch} from "react-router-dom";
import { SearchBar } from "./components/search/SearchBar";
import {Login} from "./components/screens/Login";
function ShowResolutions() {
return (
<>
<ResolutionForm />
<ResolutionList />
</>
);
}
function App() {
return (
<>
<Router>
<Switch>
<Route path="/" element={<ShowResolutions />} />
<Route path="/search" element={<SearchBar />} />
<Route path="/login" element={<Login />} />
</Switch>
</Router>
</>
);
}
export default App;
The routes lead to react components that worked fine when I hadn’t added the NodeJs server.
index.js:
const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const { handleLogin } = require('./controllers/user.controller');
const bodyParser = require('body-parser');
app.use(cors());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.set('port',process.env.PORT || 3000);
app.set('app',path.join(__dirname, 'app'));
app.post('/api/login', handleLogin);
module.exports = app;
user.controller.js with the route to login:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const handleLogin = (req, res) => {
const { username, password } = req.body;
console.log("username: ", username, "password: ", password);
};
module.exports = {
handleLogin
}```