Flask app.run method does not work with WinPython 3.11.1 and next.js application: fetch failed

2024/11/20 12:26:09

When using WinPython 3.10.5 I am able to debug my flask & next.js application using the flask debug mode (to enable hot reloads):

app.run(debug=True, host=host, port=port)

However, when using WinPython 3.11.1, the flask debug mode does not work any more. The fetch command in the static part of my next application fails and I get following error in Google Chrome dev-tools console:

GET http://localhost:3000/ 500 (Internal Server Error)
react-dom.development.js:29840 Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtools
index.js:619 Uncaught TypeError: fetch failedat Object.fetch (node:internal/deps/undici/undici:11457:11)at process.processTicksAndRejections (node:internal/process/task_queues:95:5)at async apiCall (webpack-internal:///./src/pages/_app.js:30:26)at async MyApp.getInitialProps (webpack-internal:///./src/pages/_app.js:34:27)at async loadGetInitialProps (file://C:\python_env\workspace\flask_demo\front_end\node_modules\next\dist\shared\lib\utils.js:146:19)at async renderToHTML (file://C:\python_env\workspace\flask_demo\front_end\node_modules\next\dist\server\render.js:417:13)at async doRender (file://C:\python_env\workspace\flask_demo\front_end\node_modules\next\dist\server\base-server.js:1031:34)at async cacheEntry.responseCache.get.incrementalCache.incrementalCache (file://C:\python_env\workspace\flask_demo\front_end\node_modules\next\dist\server\base-server.js:1162:28)at async (file://C:\python_env\workspace\flask_demo\front_end\node_modules\next\dist\server\response-cache\index.js:99:36)
getServerError @ client.js:1
eval @ index.js:619
setTimeout (async)
hydrate @ index.js:607
await in hydrate (async)
eval @ next-dev.js:48
Promise.then (async)
eval @ next-dev.js:42
./node_modules/next/dist/client/next-dev.js @ main.js?ts=1684760846398:181
options.factory @ webpack.js?ts=1684760846398:649
__webpack_require__ @ webpack.js?ts=1684760846398:37
__webpack_exec__ @ main.js?ts=1684760846398:1094
(anonymous) @ main.js?ts=1684760846398:1095
webpackJsonpCallback @ webpack.js?ts=1684760846398:1197
(anonymous) @ main.js?ts=1684760846398:9
favicon.ico:1     GET http://localhost:3000/favicon.ico 500 (Internal Server Error)

a) If I manually enter the fetched url http://localhost:5000/api/id_mode in an extra tab, I get the expected result from the flask application.

b) If I run the flask application with the waitress serve function (=without debug mode) instead of using app.run(...) , the application works just fine. Therefore, it does not seem to be a JavaScript issue.

serve(app, host=host, port=port)

Project file structure:

enter image description here

Python code in main.py:

import sys
from flask import (Flask,jsonify
)
from flask_cors import CORS
from waitress import servedef main():# workaround to fix issue with relative path to python in PyCharm for debugging# Also see# https://gitlab.cc-asp.fraunhofer.de/isi/micat/-/issues/363sys.executable = sys.executable.replace('flask_demo\\App', 'flask_demo\\..\\..\\App')app = create_app()host = 'localhost'port = 5000CORS(app, resources={r"/*": {"origins": ["http://localhost:3000"]}})app.run(debug=True, host=host, port=port)# serve(app, host=host, port=port)def create_app():app = Flask(__name__)@app.route('/api/id_mode')def hello_world():return jsonify({"status": "success","message": "Hello World!"})return appif __name__ == '__main__':main()

requirements.txt:

flask==2.3.2
flask-cors==3.0.10

Next.js application defined in _app.js:

import React from 'react';
import App from 'next/app';export default function MyApp({ Component, pageProps }) {const parameters = { ...pageProps };return <Component {...parameters} />;
}MyApp.getInitialProps = async (appContext) => {const appProperties = await App.getInitialProps(appContext);async function apiCall(){const url = 'http://localhost:5000/api/id_mode'const response = await fetch(url);const text = await response.text();return text;}const extraProperty = await apiCall()return {...appProperties,extraProperty};
};

index.js

import React from 'react';
import Router from 'next/router';export default function Index(properties) {return <>{"Hello from next.js"}</>;
}

package.json

{"name": "flask_demo","version": "1.0.0","main": "index.js","scripts": {"dev": "cross-env NODE_OPTIONS='--inspect' next dev"},"dependencies": {"next": "13.4.3"},"devDependencies": {"cross-env": "7.0.3"}
}

Output in Network tab:

enter image description here

Related:

PyCharm runs a flask app but fails to debug it in python3.11

next.js fetch request gives error TypeError: fetch failed

Answer

Replacing localhost with 127.0.0.1 in the url for the fetch command in the next.js front end fixed the issue.

First I missed the fact, that when updating WinPython, I did not only update python from 3.10.5 to 3.11.1, but also updated the node version from v16.16.0 to v18.12.1.

Then I found the related question next.js fetch request gives error TypeError: fetch failed

It's interesting that localhost does work when using waitress serve function instead of app.run. I guess that the two approaches to start flask rely on different implementations regarding localhost vs 127.0.0.1.

https://en.xdnf.cn/q/118418.html

Related Q&A

Pythonic way to assign global administrator roles for Azure Active Directory

What specifically needs to be changed in the Python 3 code below in order to successfully assign the Global Administrator role for an Azure Active Directory Tenant to a given service principal? We tri…

Pandas calculating age from a date

I really need help with this one. My previous post was very bad and unclear - Im sorry - I wish I could delete but hopefully this one will be better.I need to calculate the age based off of a date (se…

Create new folders within multiple existing folders with python

I am looking for a way to create new folders within multiple existing folders. For example I have folders a,b,c.. etc and I want to create a new folder inside each of these existing folders and name th…

extract a column from text file

I have a a text file (huge amount of float numbers) with 25 columns. I want to extract column 14 and divide it by column 15. I could not extract this two columns. Codes:with open(sample for north.txt) …

kivy buildozer Compile Error pythonforandroid.toolchain

Compile platformCommand failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=main -- bootstrap=sdl2 --requirements=kivy,python3 --arch armeabi- v7a --copy-libs --color=always --…

Django Error: No FlatPage matches the given query

SITE_ID = 1and (r, include(django.contrib.flatpages.urls)), is in urls.py.What can I do to fix this error? Django is still displaying this error - I have googled and I cant find anything.File urls.pyf…

I need to automate the filling of a HTML form in a web browser, how?

I am trying to build a python script that captures my screen (a website will be opened), finds the coordinates of a text entry box on the displayed web site, and then clicks in that text entry box. I a…

Page not found (404) at /user_signup in Django

Getting 404 error on signup and some more URLs. /login, /logout, /admin is working perfectly. Im making a web app that lets a user login, logout, search a flight, book a flight and view the bookings ma…

tensorflow:Your input ran out of data when using custom generator

I am using custom generator to pass my data. But i keep encountering an error which says i have run out of data and to use repeat() when passing the dataset. i am using plain generator therefore it is …

script to get the max from column based on other column values

I need a script to read in a csv file(orig.csv) and output a reformatted csv file(format.csv) The orig csv file will look like this: Time,Label,frame,slot,SSN,Board,BT,SRN,LabelFrame,SRNAME,LabelID,Int…