Rob*_*Rob 25 javascript fetch-api
我知道使用新的Fetch API(在这里使用ES2017的async/ await),您可以像这样发出一个GET请求:
async getData() {
try {
let response = await fetch('https://example.com/api');
let responseJson = await response.json();
console.log(responseJson);
} catch(error) {
console.error(error);
}
}
Run Code Online (Sandbox Code Playgroud)
但是你如何发出POST请求呢?
hel*_*bus 57
简而言之,Fetch还允许您传递一个对象以获得更个性化的请求:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
Run Code Online (Sandbox Code Playgroud)
查看获取文档以获取更多好东西和陷阱:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
请注意,既然你正在进行异步try/catch模式,你只需省略then()我的例子中的函数;)
Tel*_*nse 10
2021 答案:以防万一您在这里寻找如何使用 async/await 或 Promise 与 axios 相比进行 GET 和 POST Fetch api 请求。
我正在使用 jsonplaceholder fake API 来演示:
使用 async/await 获取 api GET 请求:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Run Code Online (Sandbox Code Playgroud)
使用 async/await 获取 api POST 请求:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
Run Code Online (Sandbox Code Playgroud)
使用 Promise 的 GET 请求:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
Run Code Online (Sandbox Code Playgroud)
使用 Promise 的 POST 请求:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
Run Code Online (Sandbox Code Playgroud)
使用 Axios 获取请求:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
Run Code Online (Sandbox Code Playgroud)
使用 Axios 的 POST 请求:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()
Run Code Online (Sandbox Code Playgroud)
如果你想发一个简单的帖子请求而不发送数据作为JSON.
fetch("/url-to-post",
{
method: "POST",
// whatever data you want to post with a key-value pair
body: "name=manas&age=20",
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((response) =>
{
// do something awesome that makes the world a better place
});
Run Code Online (Sandbox Code Playgroud)
将表单数据 POST 到 PHP 脚本的最佳方法是Fetch API。下面是一个例子:
function postData() {
const form = document.getElementById('form')
let data = new FormData()
data.append('name', form.name.value)
fetch('../php/contact.php', {
method: 'POST',
body: data,
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok.')
}
}).catch(console.error)
}Run Code Online (Sandbox Code Playgroud)
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>Run Code Online (Sandbox Code Playgroud)
这是一个非常基本的 PHP 脚本示例,它接收数据并发送电子邮件:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test@example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41257 次 |
| 最近记录: |