简体   繁体   中英

ajax fail to POST on API

i tried everything, and i still cant figure out whats the problem, i'm trying to 'POST' something on teachers server that we had for homework, and i have no idea what i'm doing wrong ,i'm stuck for like 2 hours already.

here is my code.

const xhr = new XMLHttpRequest();
const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees';
let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'});
xhr.responseType = 'json';
xhr.onreadystatechange = function(){
  if(xhr.readyState === XMLHttpRequest.DONE){
    console.log(xhr.response);
  }
}
xhr.open('POST',url);
xhr.send(attendee);

Please see this snippet, you are getting The 401 Unauthorized error , you have to attach authorization token variable to the request.
xhr.setRequestHeader('Authorization', '~Token~');

There will be an other api that will get authorization token.

 const xhr = new XMLHttpRequest(); const url = 'https://3uc5taw99i.execute-api.us-east-1.amazonaws.com/latest/attendees'; let attendee = JSON.stringify({firstName: 'Nikola',lastName:'Nikola',email:'Nikola',dateBirth:'13.12.1869'}); xhr.responseType = 'json'; xhr.onreadystatechange = function(){ if(xhr.readyState === XMLHttpRequest.DONE){ console.log(xhr.response); } else{ console.log(xhr.status); } } xhr.open('POST',url); xhr.send(attendee); 

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