我是靠谱客的博主 发嗲帆布鞋,这篇文章主要介绍反向代理设置/axios请求数据项目需求,现在分享给大家,希望可以做个参考。

项目需求

  • 项目中遇到请求跨域问题,我们一般需要项目中配置代理解决。
    项目用create-react-app2生成后
  • 首先安装包 http-proxy-middleware
复制代码
1
2
3
4
npm install http-proxy-middleware --save # or yarn add http-proxy-middleware
  • 然后在src目录下创建 setupProxy.js 文件(一定要在src根目录里面)
    最后设置代理
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// setupProxy.js(请求亲亲网和猫眼电影数据) const proxy = require('http-proxy-middleware') module.exports = function(app) { app.use( proxy('/index.php', { //`api`是需要转发的请求 target: 'http://qinqin.net', // 这里是接口服务器地址 changeOrigin: true, }) ) app.use(proxy('/ajax',{//猫眼电影数据 target:'http://m.maoyan.com', changeOrigin:true })) }
  • 然后在需要数据的组件页面中获取并渲染数据(这里举例商品详情页获得数据)
  • 安装axios转换请求数据和响应数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//srcpagescategoryindex.js文件 import React, { Component } from 'react' import './index.scss' import Slider from './Slider' import axios from 'axios' export default class Category extends Component { constructor(props) { super(props) this.state = { data: [] } } componentDidMount () { axios({ url: '/index.php', params: { r: 'class/category', type: 1 } }).then( res => { res.data.data.data.map( item => { item.title = item.name return ; }) this.setState({ data: res.data.data.data }) }) } render() { return ( <div className = "container"> <Slider { ...this.state }/> </div> ) } }
  • 最后在组件中渲染数据
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//srcpagescategorySlider.js文件 import React from 'react' import { Tabs, WhiteSpace } from 'antd-mobile';//第三方插件库 import Content from './Content' export default class Slider extends React.Component { renderContent = tab => { return ( <div style={{ height: '100%', overflow:'auto',backgroundColor: '#fff' }}> { tab.floors.map( (item,index) => <Content key = { index } { ...item } />)} </div> ); } render() { const { data } = this.props return ( <Tabs tabs={ data } renderTabBar={props => <Tabs.DefaultTabBar {...props} page={ 11 } />} tabBarPosition = "left" tabDirection = "vertical" > {this.renderContent} </Tabs> ); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//srcpagescategoryContent.js文件 import React, { Component,Fragment } from 'react' import { Link } from 'react-router-dom' const Content = props => { const renderList = list => { return list.map( item => ( <li key = { item.api_cid}> <Link to = {{ pathname: `/list/${ item.api_cid }`, search: `cid=${ item.api_cid }&a=1` }} > <img src = { item.img }/> <span> { item.name } </span> </Link> </li> )) } return ( <Fragment> <div className = "floor"> <h3 style = {{ margin: 0}}> { props.name } </h3> <ul> { renderList( props.list) } </ul> </div> </Fragment> ) } export default Content
  • 所有组件最终在App.js文件中引用

最后

以上就是发嗲帆布鞋最近收集整理的关于反向代理设置/axios请求数据项目需求的全部内容,更多相关反向代理设置/axios请求数据项目需求内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部