ajax fail to POST on API - javascript

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);

Related

Postman is giving me the outputs of this endpoint but my localhost is giving me 400 error

Dont worry about the api_key as I am doing this just for practice. Earlier it was showing CORS error so i disabled it in chrome. But now its giving me GET https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972 400 error.
function sendRequest () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972",true);
xhr.setRequestHeader("Accept","application/json");
xhr.setRequestHeader("Authorization", "Bearer {i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx}");
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
console.log(users)
}
}
xhr.send(null);
}
use it
function sendRequest () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972",true);
xhr.setRequestHeader("Accept","application/json");
xhr.setRequestHeader("Authorization", "Bearer i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx");
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
console.log(users)
}
}
xhr.send(null);
}
the { and } used for env and variable in postman (or other softwares usually)
in raw http request :
GET https://api.yelp.com/v3/businesses/search?term=delis&latitude=37.786882&longitude=-122.399972
Accept: application/json
Authorization: Bearer i6LdgRRNDolECGnS0Q7MQf5c3-nNV9rciQdmNy6x0jBFGtBv8DlnCSd2erPEOlKOb6m63MFMj0UzEEINB58fmdZBgy0bW75qfrb4BtRQxZGFcmqczb3vFXjK6G9qYXYx
postman have a feature that export requests in different programming language, use it to see efferent (link)

Storing XHR request into javascript variable

I am having trouble storing the response of my XHR request.
Here is the javascript so far:
var req = new XMLHttpRequest;
req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
req.responseType = 'json';
req.send();
Over at chrome dev tools, i can see that response is the items i want so request should be fine. It is status of 200 and state 4.
The problem becomes when i try to write
var myJSON = req.response;
When i log this to console it responds with "null".
But if i reassign the value through dev tools, to exactly the same value, i get my JSON object.. Can someone please explain to me why and how i can fix this?
try with ready state
var req = new XMLHttpRequest;
req.open('get', 'https://jsonplaceholder.typicode.com/todos', true);
req.responseType = 'json';
req.send();
req.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.response);
var myJSON = this.response;
}
};

XMLHTTPRequest POST getting stuck

I am trying to POST to a google maps service. If you click on the URL you will see the JSON response that I am expecting to get
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
However, this code gets stops after xhr.onload = function(). So I never get the response back. Is there an error in my code?
You forgot to send the request.
xhr.send("The string of application/x-www-form-urlencoded data you are POSTING goes here");
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest()
var url = "https://maps.googleapis.com/maps/api/directions/json?origin=Exeter&destination=Deal&region=uk&mode=driving"
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// do something to response
alert(this.responseText)
}
xhr.send("data to be send");
Try this.

Status code from XMLHttpRequest is returning as 0. Tried everything to rectify but hasnt worked till now

I am trying to run the following JS code locally on my computer as well as on codepen and in both places its returning me a status of 0, even though the link generated is perfectly fine. What can be the issue here? Have tried searching the net for cross-domain issues and have tried to set a NODE server/set headers explicitly to allow cross domain request, but nothing has worked till now.
window.onload = function(){
let search = document.querySelector('input');
const API_URL = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json";
search.addEventListener('change', function(){
let term = this.value;
let url = `${API_URL}&search=${term}`;
console.log(url);
let xhr = new XMLHttpRequest();
xhr.onload = function(){
if(xhr.status === 200){
console.log("ok");
}
};
xhr.open('GET', url, true);
xhr.send(null);
console.log(xhr.status);
});
};
The xhr.status is available inside the onload method, status is only set after the onload method has been called.
xhr.onload = function(){
console.log(xhr.status);
if(xhr.status === 200){
console.log("ok");
}
};

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

Categories