DEV Community

Discussion on: JavaScript And Fetch

Collapse
 
raddevus profile image
raddevus • Edited

I love the fetch() api. It's really great and makes async calls so much easier than in past with xhr. I tried your code from the browser console.

Here's one that you can try in the browser console (F12).

fetch( 'https://jsonplaceholder.typicode.com/posts' 
        ,{
            method: 'POST',
            body: JSON.stringify({first:50}),
            headers: {
              'Content-type': 'application/json',
               'charset':'UTF-8'
            }
      })
      .then((response) => response.text())
      .then((text) => console.log(text));
Enter fullscreen mode Exit fullscreen mode

Just copy and paste into the console and hit ENTER.

Also, if you change that response.text() to response.json() you get a nice JSON object back.

console output

Collapse
 
kiranrajvjd profile image
Kiran Raj R

I need to get data from the form fields and input it into the fetch to post the data to the site, that's why I use the last example code block and I forget to explain it. I love the simplicity of your code and its a good way to show the examples, clean, thank you