How to use GET and POST with fetch in JavaScript (Basic)
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
This article summarizes how to use GET and POST with fetch in JavaScript.
⇨ Click here for the Vue article index ⇨ Click here for the React article index
Conclusion
GET
function test() {
fetch("/test")
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
}
POST
function test() {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
// Write the data to send here
//name: 'name',
//title: 'title'
}),
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
}
Adding Laravel's CSRF token
function test() {
fetch(url, {
method: "POST",
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
"Content-Type": "application/json",
},
body: JSON.stringify({
// Write the data to send here
//name: 'name',
//title: 'title'
}),
})
.then(response => response.json())
.then(data => {
console.log(data)
})
.catch(err => {
console.log(err)
})
}
Explanation
The writing process itself is almost the same as Ajax or axios, so there should be no sense of discomfort.
However, when using response data,
.then((response) => response.json())
.then((data) => {
console.log(data);
})
You need to read the result once using .json() on the response.
Summary
That's all.
This page of the documentation provides a detailed explanation, but I have presented some minimal examples here.
I hope it can be helpful for someone.
For complaints or corrections, please contact me via DM on Twitter below.
That's it!