Flask app.run方法在WinPython 3.11.1和next.js应用中无法正常工作:获取失败。

huangapple go评论73阅读模式
英文:

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

问题

在使用 WinPython 3.11.1 时,Flask 的调试模式不再起作用。在 Google Chrome 开发者工具控制台中,静态部分的 Next 应用中的 fetch 命令失败,错误信息如下:

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 failed
...

手动在新标签页中输入获取的 URL http://localhost:5000/api/id_mode 可以从 Flask 应用中获得预期结果。

使用 waitress 的 serve 函数(即不使用调试模式,而是使用 app.run(...))运行 Flask 应用时,应用正常工作。因此,这似乎不是 JavaScript 问题。

英文:

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 failed
    at 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:

Flask app.run方法在WinPython 3.11.1和next.js应用中无法正常工作:获取失败。

Python code in main.py:

import sys
from flask import (
    Flask,
    jsonify
)
from flask_cors import CORS
from waitress import serve

def 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/363
    sys.executable = sys.executable.replace('flask_demo\\App', 'flask_demo\\..\\..\\App')

    app = create_app()
    host = 'localhost'
    port = 5000
    CORS(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 app


if __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:

Flask app.run方法在WinPython 3.11.1和next.js应用中无法正常工作:获取失败。

Related:

https://stackoverflow.com/questions/76242327/pycharm-runs-a-flask-app-but-fails-to-debug-it-in-python3-11/76263800#76263800

https://stackoverflow.com/questions/74165121/next-js-fetch-request-gives-error-typeerror-fetch-failed

答案1

得分: 0

在下一个.js前端的fetch命令中,将localhost替换为127.0.0.1解决了问题。

首先,我错过了一个事实,即在更新WinPython时,我不仅将python从3.10.5更新到3.11.1,还将node版本从v16.16.0更新到v18.12.1。

然后,我找到了相关的问题https://stackoverflow.com/questions/74165121/next-js-fetch-request-gives-error-typeerror-fetch-failed

有趣的是,在使用waitress的serve函数而不是app.run时,localhost可以正常工作。我猜想启动flask的这两种方法在localhost127.0.0.1方面依赖于不同的实现。

英文:

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 https://stackoverflow.com/questions/74165121/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.

huangapple
  • 本文由 发表于 2023年5月17日 22:51:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定