react-github案例

github案例

一 react脚手架配置代理_方法一

需要理解的概念有:

  • axios模块的安装与使用
  • 什么是跨域
  • 跨域的解决方案有哪些
  • proxy的限制有什么

https://cra.docschina.org/docs/proxying-api-requests-in-development

测试代理服务器项目:http://qn.chinavanes.com/test_proxy_server.zip

在package.json中追加如下配置

"proxy":"http://localhost:5000"

说明:

  1. 优点:配置简单,前端请求资源时可以不加任何前缀。
  2. 缺点:不能配置多个代理。
  3. 工作方式:上述方式配置代理,当用Ajax请求了3000不存在的资源时,那么该请求会转发给5000 (优先匹配前端资源)

src/App.js

import React, { Component } from 'react';
import axios from 'axios';
class App extends Component {
	render() {
		// 解构赋值
		return <div className='todo-container'></div>;
	}
	componentDidMount() {
		this.getData();
	}
	getData = () => {
		axios.get('/students').then((res) => {
			console.log(res);
		});
	};
}
export default App;

package.json

proxy不能是数组,只能是单一代理地址,不能代理多个。

{
   
  "name": "hello-react",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
   
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "axios": "^0.21.1",
    "nanoid": "^3.1.23",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
   
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
   
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
   
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
   
    "@babel/plugin-transform-runtime": "^7.14.2",
    "@babel/preset-flow": "^7.13.13"
  },
  "proxy": "http://localhost:5000"
}

二 react脚手架配置代理_方法二

需要理解的概念有:

  • 代理中间件的使用
  1. 第一步:创建代理配置文件

    在src下创建配置文件:src/setupProxy.js
    
  2. 编写setupProxy.js配置具体代理规则:

    const proxy = require('http-proxy-middleware')
    // 默认已经安装,不需要再安装
    
    module.</
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值