0

I making http calls to my api using AWS API Gateway and lambda proxy Integration when trying to access values in the response it says that it's "undefined", what am I doing wrong? (working with postman)

this is the response with cors enabled:


    {
        'statusCode': 200, 
        'headers': {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
        }, 
        'isBase64Encoded': False,
        'body': '{"error": "mail_taken"}'
}

the fetch code:

addUser(fullName, gender, ID, phone, email, notes, pass){
    var myHeaders = new Headers();
    var Response;
    myHeaders.append("Content-Type", "application/json");
    var raw = JSON.stringify({"main_task":"log","sub_task":"add_user","full_name":fullName,"gender":gender,"email":email,"id":ID,"phone":phone,"notes":notes,"password":pass});
    return fetch (url, {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      mode: 'cors'
    })
  }
var Response;
this.logUser.addUser(this.form.fullName, this.form.gender, this.form.ID,
    this.form.pass,this.form.email,this.form.notes,this.form.pass).then(response => response.json()
    ).then(data => Response = data);
ofek edut
  • 31
  • 1
  • 5
  • It sounds like you're trying to use `Response` before the fulfillment handler setting it was called. It's almost never best practice to use a fulfillment handler to set a variable it closes over like that. See the linked question's answers for more. – T.J. Crowder Jun 01 '20 at 07:58
  • Separately, your code is falling prey to the footgun in the `fetch` API: You're not checking for HTTP success. (Sadly, `fetch` only rejects on *network* error.) You need to check `response.ok` before calling `response.json`. More [on my anemic little blog](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder Jun 01 '20 at 07:59

0 Answers0