跨域代理
在React中需要自行安装插件实现跨域代理
①安装代理插件
项目根目录下执行
npm i http-proxy-middleware
②建立配置文件
// src/setupProxy.js 文件路径 名称和路径要严格一致
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
// 插件使用方式
// 代理配置段 代理多个段 多个app.use
app.use(
createProxyMiddleware("/douyu", {
target: "https://m.douyu.com",
changeOrigin: true,
secure: true,
pathRewrite: {
"^/douyu": "",
},
})
);
};
③进行页面渲染
import React, { Component } from "react";
import "./App.css";
export default class App extends Component {
state = { data: null };
componentDidMount() {
this.getData();
}
// 数据请求方法
getData(page=1) {
// const url = "https://m.douyu.com/api/room/list?page=1&type=yz";
const url = "/douyu/api/room/list?page=" + page + "&type=yz";
// 第一段 地址参数
// 第二段 res返回数据 格式化为json对象
fetch(url)
.then((res) => res.json())
.then((res) => {
console.log(res);
this.setState({ data: res.data });
});
}
// 拼接渲染
show = () =>
this.state.data.list.map((item, index) => (
<div key={index} className="douyu-cell">
<div>
<img src={item.roomSrc} />
<div>{item.hn}</div>
<div>{item.nickname}</div>
</div>
<div>{item.roomName}</div>
</div>
));
render() {
// 判断当异步请求数据 没有返回前不去渲染页面
if (this.state.data === null) return <div></div>;
// 获取当前页和最大页数
const { nowPage, pageCount } = this.state.data;
return (
<div>
<button
onClick={this.getData.bind(this, nowPage - 1)}
disabled={nowPage == 1}
>
上一页
</button>
<button
onClick={this.getData.bind(this, nowPage + 1)}
disabled={nowPage == pageCount}
>
下一页
</button>
{this.show()}
</div>
);
}
}