Able to send or receive data either in body or in URL params Flashcards
fetch()
- 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.
Sending Data in the Request Body
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.
Sending Data in URL Parameters
- 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
Receiving Data from the Response Body
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.
Receiving Data from URL Parameters
- 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.