简体   繁体   English

来自flask后端的反应前端响应错误

[英]React frontend response error from flask backend

I'm creating a react app that utilizes a flask backend that serves as a REST API.我正在创建一个使用作为 REST API 的 Flask 后端的 React 应用程序。 Unfortunately, I've been having issues with the fetch command, in that it always seems to say fetch failed loading: [method].不幸的是,我一直遇到 fetch 命令的问题,因为它似乎总是说 fetch failed loading: [method]。 The backend seems to handle the request fine.后端似乎可以很好地处理请求。

127.0.0.1 - - [20/Jul/2021 21:10:35] "GET /api/login HTTP/1.1" 200 - 127.0.0.1 - - [20/Jul/2021 21:10:35] "GET /api/login HTTP/1.1" 200 -

I've tried the request in postman and it works fine.我已经尝试过邮递员的请求,它工作正常。 I'm using a proxy for HTTP://localhost:5000 in my package.json so I don't think this is a CORS problem, and I've also tried using flask_cors to no avail.我在package.json使用了HTTP://localhost:5000的代理,所以我认为这不是 CORS 问题,我也尝试过使用 flask_cors 无济于事。 Has anyone experienced something like this before with fetch API?有没有人在使用 fetch API 之前经历过这样的事情? I'm fairly new to javascript so there may be something I'm not noticing.我对 javascript 还很陌生,所以可能有一些我没有注意到的地方。

Thanks.谢谢。

Users.py (blueprint) Users.py(蓝图)

from . import bp
from flask import jsonify, request, make_response

@bp.route('/login', methods=['GET'])
def login():
return jsonify({'status': 'success'})

init .py (blueprint) init .py(蓝图)

from flask import Blueprint

bp = Blueprint('rest', __name__)

from . import users

init.py (app) init.py(应用程序)

def create_app():
    from .config import Config

    app = Flask(__name__)
    app.config.from_object(Config)
    mail = Mail(app)


    from .models import db, Visitor, User
    db.init_app(app)
    migrate = Migrate(app, db)

    @app.shell_context_processor
    def make_shell_context():
        return {"config": Config, "db": db, "Visitor": Visitor, "User": User}

    #jwt.init_app(app)
    app.register_blueprint(api_bp, url_prefix='/api')
    return app

Request (from react button event handler)请求(来自反应按钮事件处理程序)

    export default function LoginUser(props) {

    const [user, setUser] = useState({})

    function handleChange(e) {
        const { name, value } = e.target

        switch (name) {
            case 'email':
                setUser({ ...user, email: value });
                break;

            case 'password':
                setUser({ ...user, password: value });
                break;

            default:
                break;
        }
    }

    function handleSubmit(e) {

        fetch('/api/login').then(res => res.json()).then().catch(error => console.log('error'))
    }

    return (
        <Form>
            <Form.Group className="mb-3" controlId="LoginEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email"
                    placeholder="Enter email"
                    name="email"
                    onBlur={handleChange} />
            </Form.Group>

            <Form.Group className="mb-3" controlId="LoginPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control type="password"
                    placeholder="Password"
                    name="password"
                    onBlur={handleChange} />
            </Form.Group>
            <Button variant="primary" type="submit" onClick={handleSubmit}>
                Submit
            </Button>
        </Form>
    )
}

Browser error (Brave)浏览器错误(勇敢)

handleSubmit @ main.chunk.js:781
callCallback @ vendors~main.chunk.js:24274
invokeGuardedCallbackDev @ vendors~main.chunk.js:24323
invokeGuardedCallback @ vendors~main.chunk.js:24383
invokeGuardedCallbackAndCatchFirstError @ vendors~main.chunk.js:24398
executeDispatch @ vendors~main.chunk.js:28633
processDispatchQueueItemsInOrder @ vendors~main.chunk.js:28665
processDispatchQueue @ vendors~main.chunk.js:28678
dispatchEventsForPlugins @ vendors~main.chunk.js:28689
(anonymous) @ vendors~main.chunk.js:28900
batchedEventUpdates$1 @ vendors~main.chunk.js:42585
batchedEventUpdates @ vendors~main.chunk.js:24072
dispatchEventForPluginEventSystem @ vendors~main.chunk.js:28899
attemptToDispatchEvent @ vendors~main.chunk.js:26382
dispatchEvent @ vendors~main.chunk.js:26300
unstable_runWithPriority @ vendors~main.chunk.js:56804
runWithPriority$1 @ vendors~main.chunk.js:31680
discreteUpdates$1 @ vendors~main.chunk.js:42602
discreteUpdates @ vendors~main.chunk.js:24084
dispatchDiscreteEvent @ vendors~main.chunk.js:26266

Try to change尝试改变

fetch('/api/login').then(res => console.log(res)).catch(error => console.log('error')) to fetch('/api/login').then(res => res.json()).then(result => console.log(result)).catch(error => console.log('error')) . fetch('/api/login').then(res => console.log(res)).catch(error => console.log('error'))fetch('/api/login').then(res => res.json()).then(result => console.log(result)).catch(error => console.log('error'))

Because using fetch, your 'res' is just an HTTP response, not the actual JSON.因为使用 fetch,你的 'res' 只是一个 HTTP 响应,而不是实际的 JSON。 So you need res.json() to get the JSON body.所以你需要 res.json() 来获取 JSON 正文。

Edit version编辑版本

Change <Button variant="primary" type="submit" onClick={handleSubmit}> to <Button variant="primary" type="submit" onClick={(e)=>handleSubmit(e)}> .<Button variant="primary" type="submit" onClick={handleSubmit}>更改为<Button variant="primary" type="submit" onClick={(e)=>handleSubmit(e)}> Also add e.preventDefault() in the handleSubmit function to prevent the page from refreshing.还要在handleSubmit 函数中添加e.preventDefault()以防止页面刷新。

Note: You should pass your user in api login注意:您应该在 api login 中传递您的用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM