系列文章
测开技能--Web开发 React 学习(一)
测开技能--Web开发 React 学习(二)环境搭建
测开技能--Web开发 React 学习(三)元素的渲染
测开技能--Web开发 React 学习(四)元素的动态渲染
测开技能--Web开发 React 学习(五)JSX
测开技能--Web开发 React 学习(六)组件
测开技能--Web开发 React 学习(七)提取组件
测开技能--Web开发 React 学习(八)Props 的只读性
测开技能--Web开发 React 学习(九)条件渲染
测开技能--Web开发 React 学习(十)表单
测开技能--Web开发 React 学习(十一)
这是第十二篇文章。
我们写前端页面,少不了,和后端打交道,需要的就是网络请求,那么我们怎么来进行网络请求
呢,其实很简单,直接使用fetch。
请求的方法一般放在生命周期的componentDidMount里
我们去实现。
import React, { Suspense } from 'react';import 'antd/dist/antd.css';import { Layout, Menu, Breadcrumb } from 'antd';import './home.css'import { DesktopOutlined, PieChartOutlined,UserOutlined,CarOutlined,SettingOutlined,ApiOutlined} from '@ant-design/icons';const { SubMenu } = Menu;const { Header, Content, Footer, Sider } = Layout;class SiderDemo extends React.Component { constructor(props){ super(props) this.state={ } } componentDidMount(){ fetch("http://openapi.tuling123.com/openapi/api/v2",{ method:'POST', mode:"cors" }).then(res=>res.json()).then((data)=>{ console.log(data) }) } state = { collapsed: false, }; onCollapse = collapsed => { console.log(collapsed); this.setState({ collapsed }); }; render() { return ( ); }} export default SiderDemo
我们去启动访问,结果报错,
那么,我们怎么去解决跨域问题呢。
我们可以看下官网文档给我的方式,
https://github.com/facebook/create-react-app/blob/master/docusaurus/docs/proxying-api-requests-in-development.md#configuring-the-proxy-manually
我们可以直接在package.json 配置porxy 即可。
"proxy":"http://openapi.tuling123.com"
配置后 我们重启服务,把fetch 改成
fetch("/openapi/api/v2",{ method:'POST', mode:"cors" }).then(res=>res.json()).then((data)=>{ console.log(data) })
这样就可以解决这个问题。
这是打印输出来的结果
另外的方案也是可以的直接,
这是我们大概的一个的请求,以及如何解决跨域的问题,我们接下来肯定还是有很多的请求要写的,我们是不是需要封装下,利用封装后,再来封装后的方法再来解决呢。
欢迎持续关注雷子说测试开发。