JavaScript 中的fetch()方法 用于向服务器请求并加载网页中的信息。请求可以是返回 JSON 或 XML 格式数据的任何 API。此方法返回一个承诺。

句法:

fetch( url, options )

参数:此方法接受上面提到的两个参数,如下所述:

  • URL:这是要向其发出请求的 URL。
  • 选项:它是一组属性。它是一个可选参数。

返回值:它返回一个承诺,无论它是否已解决。返回数据的格式可以是 JSON 或 XML。
它可以是对象数组,也可以是单个对象。

示例 1:

注意:如果没有选项,Fetch 将始终充当获取请求。

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content=
	"width=device-width, initial-scale=1.0">

	<title>JavaScript | fetch() Method</title>
</head>

<body>
	<script>

		// API for get requests
		let fetchRes = fetch(
"https://jsonplaceholder.typicode/todos/1");

		// fetchRes is the promise to resolve
		// it by using.then() method
		fetchRes.then(res =>
			res.json()).then(d => {
				console.log(d)
			})
	</script>
</body>

</html>

输出:

使用 Fetch 发出 Post 请求:可以使用 fetch 通过提供以下选项来发出 Post 请求:

let options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(data)
}

示例:2

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content=
		"width=device-width, initial-scale=1.0">

	<title>JavaScript | fetch() Method</title>
</head>

<body>
	<script>
		user = {
			"name": "Geeks for Geeks",
			"age": "23"
		}
		
		// Options to be given as parameter
		// in fetch for making requests
		// other then GET
		let options = {
			method: 'POST',
			headers: {
				'Content-Type':
					'application/json;charset=utf-8'
			},
			body: JSON.stringify(user)
		}

		// Fake api for making post requests
		let fetchRes = fetch(
"http://dummy.restapiexample/api/v1/create",
										options);
		fetchRes.then(res =>
			res.json()).then(d => {
				console.log(d)
			})
	</script>
</body>

</html>

输出:

 

更多推荐

JavaScript fetch() 方法