Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

reactjs - POST 400 (BAD REQUEST) error for React Native/Flask/axios app

I'm very beginner so I hope this isn't a dumb question. I've been googling this for hours and reading other posts but I can't seem to find a solution that works. Basically, I'm making an app that uses React Native for the frontend and Flask with SQLAlchemy for the backend. I'm trying to enter an email and password in my app to check if it's valid or not in the console. This is the full error:

Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

I think this would be easiest to explain by showing all the relevant code. This is in the backend where I add my test email and password to the database:

with app.app_context():
    db.create_all()
    if db.session.query(User).filter_by(email='testing').count() < 1:
        db.session.add(User(
            email='testing',
            password=guard.hash_password('testPass'),
            roles='admin'
        ))
    db.session.commit()

This is also in the backend:

@app.route('/api/login', methods=['POST'])
def login():
    req = flask.request.get_json(force=True)
    email = req.get('email', None)
    password = req.get('password', None)
    user = guard.authenticate(email, password)
    ret = {'access_token': guard.encode_jwt_token(user)}
    return ret, 200

This is where I do the axios stuff:

import axios from 'axios'

const instance = axios.create({
    baseURL: 'http://localhost:5000',
});

export default {
    
    getUser: ({ops}) =>
    instance({
        'method':'POST',
        'url':'/api/login',
    }),
}

And finally, this is in the frontend:

export default function LoginScreen() {

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const onSubmitClick = ()=>{
    console.log("You pressed login")
    let opts = {
      'email': email,
      'password': password
    }
    console.log(opts)
    api.getUser(JSON.stringify(opts)).then(response => response.json())
      .then(token => {
        if (token.access_token){
          console.log(token)
        }
        else {
          console.log("Please type in correct username/password")
        }
      }).catch((error) => {
            console.log(error)
        })
  }

So in the console it's showing the "You pressed login" but it throws the error after that. I have no idea why. Additionally, I did curl -X POST -d "{"email":"testing", "password":"testPass"}" 127.0.0.1:5000/api/login in my command line and it gave me the token, so in this case I know that it can go to the URL fine. Any help at all I would be eternally grateful. Thank you

question from:https://stackoverflow.com/questions/66059693/post-400-bad-request-error-for-react-native-flask-axios-app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...