
文件目录
Proxying in Development

在开发模式下,如果客户端所在服务器跟后台服务器的地址或者端口不一致,则会出现跨域的问题。
 服务器运行在3030端口:
//server/index.js
const express=require('express')
const app=express()
app.get('/api/*',(req,res)=>{
    res.send('来自服务端的响应信息!!')
})
app.listen(3030,()=>{
    console.log('服务器正在监听3030端口')
})
发送网络请求:
  
import logo from './logo.svg';
import './App.css';
import { Outlet } from 'react-router-dom';
function App() {
  const onFetch=()=>{
      //向服务器发送网络请求
    fetch('http://localhost:3030/api/user')
 }
  return (
    <div className="App">
      <button onClick={onFetch}>发送请求</button>
    </div>
 );
}
export default App;
 使用Proxy解决跨域
 在package.json中设置Proxy属性:
"proxy":"http://localhost:3030"
设置代理后,则发送的api请求会被代理服务器转发到 localhost:3030
提示:
proxy代理仅在开发中有效。
在生产环境下,这个代理无效。
http-proxy-middleware
  
 

为了更灵活的配置代理信息,我们可以使用http-proxy-middleware。
1、安装http-proxy-middleware
  
npm install http-proxy-middleware  
//或者 yarn add http-proxy-middleware2、创建src/setupProxy.js文件
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
//app为Express实例
    //使用app.use注册中间件
  app.use(
    '/api/*',
    createProxyMiddleware({
        //target:服务器地址
      target: 'http://localhost:3030',
      changeOrigin: true
   })
 );
};
fetch_get

fetch是浏览器提供的API,用于发起获取资源的请求,它返回一个 promise。
fetch(input[, init])
       input:要获取资源的 URL
       init:(可选)配置对象
       返回Promise
get
  
fetch('/api/user').then(res=>{
      // res是响应对象
      //返回的body是字符串,所以使用text()读取
      return res.text()
   }).then(data=>{
      console.log(data)
   })
传递参数
//get请求传递参数
fetch('/api/user?name=baizhan').then(res=>{
      // res是响应对象
      //返回的body是json,所以使用json()读取
      return res.json()
   }).then(data=>{
      console.log(data)
   })
fetch 是否成功

 当遇到网络错误时, fetch() 返回的 promise 会被 reject。成功的 fetch() 检查不仅要包括 promise 被 resolve,还要判断下status,HTTP 500或者404 状态并不被认为是网络错误,依然会返回响应对象,只不过它的ok为false。
 服务器的状态码返回500:
res.status(500).send('服务器发生错误')})fetch('/api/user').then(res=>{
      // res是响应对象
      console.log(res)
        return res.text()
   }).then(data=>{
      console.log(data)
   }).catch(e=>{
      // catch捕获不到我们预期的错误
   })应当判断响应信息的status或者ok是否为true,否则抛出错误
  
fetch('/api/user').then(res=>{
      // res是响应对象
      console.log(res)
      if(res.status==200){
        return res.text()
     }
      throw new Error('响应发生错误')
   }).then(data=>{
     // 抛出错误,则这个回调函数并不会被调用
      console.log(data)
   }).catch(e=>{
      // 抛出错误,catch捕获,可以编写处理错误的逻辑
   })
axios

Axios 是一个基于 promise 网络请求库。
1、安装axios
npm instal axios
//或者yarn add axiosget
axios.get('/api/user',{params: {name:'xiaotong'}}).then(res=>{
      console.log(res.data)
   })
post
//传递json数据  
axios.post('/api/user', {name:'xiaotong'}).then(res=>{
      console.log(res.data)
   })
//传递表单数据  
axios.post('/api/user',{name:'xiaotong'},{
      headers:{"Content-Type":"application/x-www-form-urlencoded"}
   }).then(res=>{
      console.log(res.data)
   })全局处理

1、指定默认配置
 您可以指定默认配置,它将作用于每个请求。
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2、拦截器
 在请求或响应被 then 或 catch 处理前拦截它们。
  
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      config.headers['Authorization'] = 'xxxxxxx';
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      return config
   });
// 添加响应拦截器
  
axios.interceptors.response.use(function
(response) {
      // 2xx 范围内的状态码都会触发该函数。
      // 对响应数据做点什么
      console.log(response)
      return response
   }, function (error) {
      // 超出 2xx 范围的状态码都会触发该函数。
      // 对响应错误做点什么
      console.log(error)
      
   })
antd UI库

 antd 是基于 Ant Design 设计体系的 React UI 组件库,主要用于研
 发企业级中后台产品。
1、安装antd
npm install antd
//或者yarn add antd2、使用antd
//AntdTest.js
import React from 'react';
import { Button, DatePicker } from 'antd'
export default function index() {
    return (
        <div >
            <Button type='primary'>我是来自antd的按钮</Button>
            <DatePicker />
        </div>
   );
}
 3、国际化
  
//index.js
import zhCN from 'antd/locale/zh_CN';
import {ConfigProvider} from 'antd'
<React.StrictMode>
    <ConfigProvider locale={zhCN}>
    <App/>
    </ConfigProvider>
  </React.StrictMode>
4、引入重置样式
  
//index.js
import 'antd/dist/reset.css';更改主题

 更改主题
 通过ConfigProvider设置主题
 切换内置主题:默认有三个内置主题(defaultAlgorithm,darkAlgorithm, compactAlgorithm)
//通过修改 ConfigProvider 中 theme 属性的 algorithm 属性来切换
import {ConfigProvider,theme} from 'antd'
//index.js
<ConfigProvider locale={zhCN} theme={{
       algorithm: theme.darkAlgorithm,
   }}>
    <App/>
  
    </ConfigProvider>
配置主题(修改主题变量)
  
<ConfigProvider
    theme={{
      token: {
        colorPrimary: '#00b96b',
     },
   }}
  >
    <App />
  </ConfigProvider>
使用Desing Token
import React from 'react';
import { Button, DatePicker ,theme} from 'antd'
export default function index() {
    //调用theme的useToken()获取当前主题下的Design Token
    const {token}=theme.useToken()
    return (
        <div >
            <Button type='primary'>我是来自antd的按钮</Button>
            <DatePicker />
           {/* 根据变量名来访问 */}
            <div style= {{color:token.colorPrimary}}>hello,xiaotong</div>
        </div>
   );
}
使用css module的情况下修改第三方库的样式

//AntdTest/index.module.css
.container :global(:where(.css-dev-only-donot-override-1ni1eeq).ant-btn-primary){
    background:red
}
:where 选择器降低 CSS Selector 优先级,以减少用户升级 v5 时额外调整自定义样式成本。
  比对:
.ant-btn-primary{
        background:red//它的优先级更高
}
:where(.css-dev-only-do-not-override-1ni1eeq).ant-btn-primary{
        background:blue
}
支持sass & less

 支持sass
        安装sass
npm install sass
或者yarn add sass      更改文件的后缀为.scss
  
支持less
      导出配置文件。
npm run eject
或者yarn run eject安装less和less-loader
  
npm install less less-loader -D
或者yarn add less less-loader -D修改webpack.config.js
//定义正则,用来查找文件以.less结尾的文件
const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
  {
              test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders(
               {
                  importLoaders: 3,
                  sourceMap: isEnvProduction
                    ? shouldUseSourceMap
                   : isEnvDevelopment,
                  modules: {
                    mode: 'icss',
                 },
               },
                'less-loader'
             ),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when ,webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
           },
            // Adds support for CSS Modules, but using SASS
            // using the extension.module.scss or .module.sass
           {
              test: lessModuleRegex,
              use: getStyleLoaders(
               {
                  importLoaders: 3,
                  sourceMap: isEnvProduction
                    ? shouldUseSourceMap
                   : isEnvDevelopment,
                  modules: {
                    mode: 'local',
                    getLocalIdent: getCSSModuleLocalIdent,
                 },
               },
                'less-loader'
             ),
           },










