I am running a Flask + React app on EC2 using Vite. Everything is running fine on when I run ‘npm run dev’ as you can see here . Its also running fine from the flask end as you can see here . The issue is when I try to run it using my prod server with my ec2 url or even when I run ‘npm run build’ and ‘npm run preview’. I get the following when i run these commands. Also, when I type in my ec2 url, i get this. and when I type in ‘ec2-url/api/hello’, i get the same console error but my page shows the classic 404 message: ‘Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. ‘
Anyways, this is what my app.py looks:
from flask import Flask, jsonify
from flask_cors import CORS
import logging
from logging.handlers import RotatingFileHandler
import os
app = Flask(__name__)
CORS(app)
# Set up logging
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/myapp.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('MyApp startup')
@app.route('/')
def hellodefault():
app.logger.info('Hello endpoint was accessed')
return jsonify(message="Hello from default Flask Route!")
@app.route('/api/hello')
def hello():
app.logger.info('Hello endpoint was accessed')
return jsonify(message="Hello from Flask!")
if __name__ == '__main__':
app.run(debug=True)
This is what my App.jsx looks:
import { useState, useEffect } from 'react'
import axios from 'axios'
import './App.css'
function App() {
const [message, setMessage] = useState('')
useEffect(() => {
const apiUrl = `${import.meta.env.VITE_API_URL}/api/hello`;
console.log('VITE_API_URL:', import.meta.env.VITE_API_URL);
axios.get(apiUrl)
.then(response => setMessage(response.data.message))
.catch(error => console.error('Error:', error))
}, [])
return (
<div className="App">
<h1>{message}</h1>
</div>
)
}
export default App
I have two .env files in my frontend directory where my react project is. one is called .env.development and contains: ‘VITE_API_URL=http://127.0.0.1:5000’
my .env.production currently contains ‘VITE_API_URL=http://ec2-xxx-amazon.com’. my vite.config.js is:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
alexis alvarez is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.