Netizens have been talking about ChatGPT by OpenAPI and I decided to try it out. My search goes thus - "Example of get and post call in JavaScript" and below is the response I got.
In JavaScript, you can use the fetch() API to make HTTP requests, such as GET and POST requests. Here's an example of a GET request:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => {
console.log(data);
});
This code uses the fetch() method to make a GET request to the specified URL. The .then() method is used to handle the response returned by the server. The first .then() method is used to parse the response as JSON, and the second .then() method is used to access the data and do something with it.
For a POST request, you can use the fetch() method along with the Request() constructor to specify the request method and the request body:
const data = { title: "foo", body: "bar", userId: 1 };
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(data);
});
This code creates a JavaScript object that represents the data to be sent to the server, and then it uses the fetch() method to make a POST request to the specified URL. The headers option is used to set the Content-Type header to application/json, and the body option is used to send the data as the request body.
Please note that these are examples only and the URLs are not real endpoints, that means that you will not get a real response from these URLs.
Also, in a real-world scenario, you should also handle errors and other edge cases, and add validations, loading spinners, and other features.
What's your thought on ChatGPT?
Top comments (0)