Able to send or receive data either in body or in URL params Flashcards

1
Q

fetch()

A
  • To send or receive data in JavaScript, you can use the built-in fetch() function.
  • The fetch() function is a promise-based API for making network requests in the browser.
  • It can be used to send and receive data either in the request body or in URL parameters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Sending Data in the Request Body

A

In this example, we create a data object that contains a username and password. We then create a fetch request with the method POST, set the headers to indicate that the content type is JSON, and set the body to contain the data object as a JSON string. We then use the then() method to parse the response body as JSON and log it to the console. If an error occurs, we catch it and log the error message.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Sending Data in URL Parameters

A
  • In this example, we create a URL search parameters object containing the query string parameters.
  • We then create a fetch request
    • with the URL that includes the query string
    • by appending it to the base URL using template literals.
  • We then use the then() method to parse the response body as JSON and log it to the console. If an error occurs, we catch it and log the error message.
  • https://www/example.com/search?q=search%20terms&categroy=books
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Receiving Data from the Response Body

A

In this example, we create a fetch request to get data from a server. We use the then() method to parse the response body as JSON and log it to the console. If an error occurs, we catch it and log the error message.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Receiving Data from URL Parameters

A
  • In this example, we create a URL search parameters object from the current URL, extract the value of the ‘q’ parameter, and use it in a fetch request to search for data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly