首页 > 其他 > 详细

Fetch请求

时间:2021-02-13 08:48:15      阅读:30      评论:0      收藏:0      [点我收藏+]

get请求

App.js

import React from ‘react‘;

import ProxyDemo from ‘./ProxyDemo‘;

export default class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			banners: [],
		};
	}

	componentDidMount() {
		/**
		 * fetch 基于promise
		 * https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
		 */

		fetch(‘http://iwenwiki.com/api/blueberrypai/getIndexBanner.php‘)
			.then((res) => res.json())
			.then((data) => {
				this.setState({
					banners: data.banner,
				});
				console.log(data.banner);
			});
	}

	render() {
		const { banners } = this.state;
		return (
			<div>
				<ProxyDemo></ProxyDemo>
				{banners.length > 0 ? (
					<ul>
						{banners.map((element, index) => {
							return <li key={index}> {element.title} </li>;
						})}
					</ul>
				) : (
					<div>等待数据加载</div>
				)}
			</div>
		);
	}
}

POST请求

import React from ‘react‘;

import ProxyDemo from ‘./ProxyDemo‘;
import qs from ‘querystring‘;

export default class App extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			banners: [],
		};
	}

	componentDidMount() {
		/**
		 * fetch 基于promise
		 * https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
		 */

		fetch(‘http://iwenwiki.com/api/blueberrypai/getIndexBanner.php‘)
			.then((res) => res.json())
			.then((data) => {
				this.setState({
					banners: data.banner,
				});
				console.log(data.banner);
			});

		fetch(‘http://iwenwiki.com/api/blueberrypai/login.php‘, {
			method: ‘POST‘,
			headers: {
				‘Content-Type‘: ‘application/x-www-form-urlencoded‘,
				Accept: ‘application/json, text/plain,*/*‘,
			},
			// body: {
			// 	user_id: ‘iwen@qq.com‘,
			// 	password: ‘iwen123‘,
			// 	verification_code: ‘crfvw‘,
			// },
			// 方法一:
			// body:
			// 	‘user_id=iwen@qq.com&password=iwen123&verification_code=crfvw‘,
			// 方法二:
			body: qs.stringify({
				user_id: ‘iwen@qq.com‘,
				password: ‘iwen123‘,
				verification_code: ‘crfvw‘,
			}),
		})
			.then((res) => res.json())
			.then((data) => {
				console.log(data);
			});
	}

	render() {
		const { banners } = this.state;
		return (
			<div>
				<ProxyDemo></ProxyDemo>
				{banners.length > 0 ? (
					<ul>
						{banners.map((element, index) => {
							return <li key={index}> {element.title} </li>;
						})}
					</ul>
				) : (
					<div>等待数据加载</div>
				)}
			</div>
		);
	}
}

Fetch请求

原文:https://www.cnblogs.com/lhongsen/p/14399206.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!