I am trying to serve both my reactjs and nodejs in one port and I have done this before. I don't know why I can't seem to get it to work. It is a MERN stack application This is my folder structure:
The app.js and build folder are all in same folder called api
Here is how I am serving the static files
app.use(cors({credentials: true,
origin: 'http://localhost:3000'
}));
app.use(express.json());
//cookie-parser
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/build')))
app.use("/api/v1/auth", authRoute);
app.use("/api/v1/users",userRoute);
app.use("/api/v1/posts",postRoute);
app.use("/api/v1/popular", PopularPosts)
app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, 'build', 'index.html'));
})
app.use(checkDB);
module.exports = app;
Then I called the API this way. Just an example of one of the API calls:
const URL = 'http://localhost:5000/api/v1'
export default function Home() {
useEffect( () => {
dispatch({ type: "ISLOADING_START" });
const fetchPosts = async ()=>{
const res = await axios.get(URL+"/posts"+search)
setPosts(res.data)
dispatch({ type: "ISLOADING_END" });
}
fetchPosts()
}, [search])
}
Here is my server connection code:
const app = require('./app');
//mongoDb
const connectDB = require('./db/connect');
//connect to mongodb server
const port = process.env.PORT || 5000;
const server = http.createServer(app);
const start = async () => {
try {
await connectDB(process.env.MONGO_URL)
server.listen(port, () =>
console.log(`Server is listening on port ${port}...`)
);
} catch (error) {
}
};
start();
I am getting this error when I tried to access the application via the backend port which is 5000
Error: ENOENT: no such file or directory, stat
'C:\Users\servi\Desktop\coding\blogfullstack\api\build\index.html'
I checked console.log and saw this error:
GET http://localhost:5000/ 404 (Not Found)
