FAQ: Requests II - async POST Requests III

This community-built FAQ covers the “async POST Requests III” exercise from the lesson “Requests II”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise async POST Requests III

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

There is an issue with Rebrandly API. I am getting the error that:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

Hi guys,

Throughout this GET and POST requests lesson I have trouble understanding how one part fit into the other.

In every POST and GET lesson in this chapter we start with writing code similar to this:

const getData = async () => {
try {
const response = await fetch(‘https://api-to-call.com/endpoint’, {
method: ‘POST’,
body: JSON.stringify({id: 200})
})
if (response.ok) {
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error(‘Request failed!’);

}
catch(error) {
console.log(error);
}
}

Then in the next step it says something like “Since you’ve created a boilerplate code for a POST request…”

I don’t understand how the first step ties into the second step with API keys etc. My getData function is nowhere to be seen in this second step. Can someone please explain their correlation?

2 Likes

In this lesson the const shortenUrl = async () => { replaces the getData = async () => { in the boilerplate code.

image

2 Likes

Hi,

Just wondering if anyone could help me understand further when I would use a GET request over a Post request and visa versa.

Thanks!

the url shortener does not work for me…I actually has never worked.
I complete the task successfully but when I paste a link, it come up with nothing.

You use a GET request when you want to retrieve information from a server.
You use a POST request when you send information to a server which the server processes and send back to you.

When we pass in the url to shorten to rebrandly, why do we create an object and then stringify it? Couldn’t we use a template literal for that property within the second parameter of fetch?

Also, shouldn’t we be using

body: await data,

if we are using stringify, and up that chain of operations as well? Or does the await on fetch apply to all its parameters as well? It doesn’t seem like that would be the case.

Same for me. The code runs but the url doesn’t shorten; even when I use codeacademy’s code. Is there a bug?

Hi!

I do not have a question about the exercise itself, but rather the helper functions section. I am struggling to understand from where res.errors and res.shortUrl come from as these are not pre-defined variables nor methods.

const renderResponse = (res) => {
  // Displays either message depending on results
  if(res.errors){
    responseField.innerHTML = "<p>Sorry, couldn't format your URL.</p><p>Try again.</p>";
  } else {  
    responseField.innerHTML = `<p>Your shortened url is: </p><p> ${res.shortUrl} </p>`;
  }
}

Thanks!

I am not a professional so I cant provide the correct answer… what I understood is its kind of related to built in object methods or the fetch function or the xhr object we learnt at the beginning.

hi, it’s either a response.method() or response.property. Remember, response is an object that has methods and properties.
if you call the renderRawResponse, you will find a property belongs to the response called shortUrl.

I noticed that the “throw new Error(‘Request failed!’)” is required only in some async GET/POST exercise, and based on the diagram provided, it is required, but in this exercise it isn’t. 1) is it or is it not required? 2) Can you, based on your experience, give me some real scenarios that will trigger the custom throw new Error and the catch(error)? what is the difference between these 2 types of errors? I’ve read that the custom new error will be raised when the response.ok is falsy, how? in what situation?..and the catch(error) will be raised when the endpoint cannot be reached at all, or the server is down…I reallt can’t relate…Can you spend a few minutes and answer my question please…I’d be very thankful. @mtf @midlindner
Thank you…

// information to reach API
const apiKey = ‘05b0ad32bd5b43ca942790b1177af2bf’;
const url = ‘https://api.rebrandly.com/v1/links’;

// Some page elements
const inputField = document.querySelector(’#input’);
const shortenButton = document.querySelector(’#shorten’);
const responseField = document.querySelector(’#responseField’);

// AJAX functions
const shortenUrl = async () => {
const urlToShorten = inputField.value
const data = JSON.stringify({destination: urlToShorten})
try{
const response = await fetch(url, {
method: ‘POST’,
body: data,
headers: {
‘Content-type’: ‘application/json’,
‘apikey’: apiKey}
} )
if (response.ok){
const jsonResponse = await response.json()
renderResponse(jsonResponse)}
}
catch(error){ **
** console.log(error)

** }}**

// Clear page and call AJAX functions
const displayShortUrl = (event) => {
event.preventDefault();
while(responseField.firstChild){
responseField.removeChild(responseField.firstChild);
}
shortenUrl();
}

shortenButton.addEventListener(‘click’, displayShortUrl);

1 Like

Is it possible you have not correctly input the API from Rebrandly?

During this course I had multiple times where I “passed” the course but was struggling to get the actual thing to work as intended. In every case, it ended up being a small typo where I had made a mistake and only by going over it with a fine-tooth comb was I able to resolve the issue.

I haven’t tried Codecademy’s code, however it may need you to input your API to work?

JSON.stringify() (the function that return the value to be saved into data) returns a string, not a promise. there is no need to use await

Same thing for me. Never worked.

Are you adding " http://" before your link. I believe you need to do this to have everything work.
image
image

@textninja83556 , you may want to check the apiKey of line 2

Excellent question. You made me check my previous lessons. It is required but here it has been omitted. Because the error didn’t happen, we didn’t see the error triggered.

The throw should be put after the closing curly bracket if the if truthy block, after this statement

renderResponse(jsonResponse)}

and should be

else {throw new Error('Request failed!')}

The throw protects the case where the Request didn’t even reach the server (network error), while the catch protects the case where the Request did reach the server but the server gave an answer where response.ok is false

It’s the opposite

Disclaimer: I’m not part of Codecademy, just another member of the community, like you.

Just wondering if I’m the only one feeling like typing same things for the last 2 hours going insane over and over again when seeing same instructions each time? Sorry guys but it feels like I need a great break to get my motivation back. Anyways I hope you are doing better and if not I send you support <3