0

I am using the fetch library from reactjs for getting and pushing data to/from my flask API. But can't get the desired response from the my api.

This is my flask api:

@app.route('/adduser',methods=['POST'])
    def indx():
    data=request.get_json(force=True)
    email=request.get_json()["email"]
    password=request.get_json()['password']
    try:
        auth.create_user_with_email_and_password(email,password)
    except:
        userexists="User Already Exists"
    try:
        user=auth.sign_in_with_email_and_password(email,password)
        id = auth.get_account_info(user['idToken'])
        db.child("users").push(id)
    except:
        invalidCredentials="Wrong Credentials"
    if request.get_json(force=True):
        x={
            "name":"sarmad",
            "roll":"052"
        }
        s=json.dumps(x)
        return s
    else:
        return ""

This is react js code:

fetch('http://127.0.0.1:5000/adduser', {
    mode:'no-cors',
 method: 'POST',
 headers: {
   'Accept': 'application/json',
   "Access-Control-Allow-Origin": "*",
    'Content-Type': 'application/json'
 },
 body: JSON.stringify({
   'email': this.state.email,
   password: this.state.password,
   name: this.state.name,
//    userType: userTy,
   dob:this.state.DOB,
   address:this.state.Address,
   gender:'male',
   phone:'090078601',
//    roles:roles
 })
}).then((response) => response).then((responseJson) => {
  console.log(responseJson);
 //this.setState({pressed: false});
})

I need to receive the data passed back from the Flask API either as a string or json. This is my current response back:

Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" _proto_: Response

Any help would be greatly appreciated!

Nathan
  • 7,853
  • 4
  • 27
  • 50
  • **Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …} body: (...) bodyUsed: false headers: Headers {} ok: false redirected: false status: 0 statusText: "" type: "opaque" url: "" __proto__: Response** This is the response i get in inspect option of browser – Rana Sarmad Rajput Feb 08 '19 at 15:00
  • Don’t use mode: 'no-cors'. See https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors/43268098#43268098 and https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors/43319482#43319482. If you specify mode: 'no-cors', the browser blocks your frontend JavaScript code from accessing the response body and response headers. That’s what 'opaque' response means. – sideshowbarker Feb 10 '19 at 05:34

1 Answers1

2

Just do it with .json()

}).then((response) => response.json()).then((responseJson) => {
  console.log(responseJson);
 //this.setState({pressed: false});
})
Sergey Pugach
  • 5,561
  • 1
  • 16
  • 31