简体   繁体   中英

React frontend response error from flask backend

I'm creating a react app that utilizes a flask backend that serves as a REST API. Unfortunately, I've been having issues with the fetch command, in that it always seems to say 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 -

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. Has anyone experienced something like this before with fetch API? I'm fairly new to javascript so there may be something I'm not noticing.

Thanks.

Users.py (blueprint)

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

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

init .py (blueprint)

from flask import Blueprint

bp = Blueprint('rest', __name__)

from . import users

init.py (app)

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')) .

Because using fetch, your 'res' is just an HTTP response, not the actual JSON. So you need res.json() to get the JSON body.

Edit version

Change <Button variant="primary" type="submit" onClick={handleSubmit}> to <Button variant="primary" type="submit" onClick={(e)=>handleSubmit(e)}> . Also add e.preventDefault() in the handleSubmit function to prevent the page from refreshing.

Note: You should pass your user in api login

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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