当前位置: 首页 > web >正文

【React】通过 fetch 发起请求,设置 proxy 处理跨域

  • fetch 基本使用
  • 跨域处理

fetch 基本使用

在node使用原生ajax发请求:XMLHttpRequest()1.获取xhr对象  2.注册回调函数  3.设置参数,请求头  4.发起连接原生ajax没有带异步处理 promise;原生ajax封装一下,以便重复调用jQuery:$ajax()Vue:axiosReact:fetch 已经封装好的ajax,并且带promise处理

src\utils\http.js(请求的封装)

/*http({url:"",method:"",params:{}  |  data:{}    --------get请求params,post请求data}).then(res=>{//在这里直接拿到数据,不想要两次.then才拿到})使用token的内容也封装进去
*/const BASE_URL = '/api'  //基础请求路径  http://172.16.235.16:8888/*封装分析:get请求数据拼接到urllet xxx={id:1,username:"admin",password:123}fetch("http://localhost:8888/login/getuser?id=1&username=admin&password=123")fetch("http://localhost:8888/login/getuser?"+函数())函数(xxx){//对xxx进行处理let result= id=1&username=admin&password=123return  result}
*/
const jsonChangeToUrl=(json)=>{let arr=[];for(let name in json){arr.push(name+"="+json[name]);  //[id=1,name=admin,pwd=123]}return arr.join("&");  //"id=1&name=admin&pwd=123"
}const http=({url,method='get',params={},data={}})=>{if(!url)return; //如果没有传递请求路径,就结束请求const token=sessionStorage.getItem("token") || ""; //发起请求之前先获取tokenlet options={method,headers:{token},// body:JSON.stringify(data)}if(method.toLowerCase()==='post'){options.body=JSON.stringify(data)}return fetch(BASE_URL+url+"?"+jsonChangeToUrl(params),options).then(response => {if(response.status === 401){ //token失效window.location.href="/login";  //浏览器url地址栏}else {return response.json();}})
}export default http;

src\pages\login\index.js (使用fetch发起请求)

import { Button,Form, Input,Radio,message } from 'antd';
import './index.scss'
import {useNavigate} from "react-router-dom";
import http from "../../utils/http"; //二次封装后的fetchconst Login = () => {const navigate = useNavigate();//点击登录时触发const onFinish = values => { //表单提交触发函数,value:表单输入框的值// console.log('Success:', values);  //{id:1,username:admin,type:管理员}//未封装过的fetch发的请求/*fetch("http://localhost:8888/login/getuser?username=201&password=201&type=管理员").then(resp => {console.log(resp)return resp.json()  //resp.json()是将返回的数据转为对象给我用;resp.text()返回的只是单纯的文本时可用}).then(data => {console.log(data)}).catch((err)=>{console.log("错误信息:"+err)})*///自己封装的fetchhttp({url:"/login/getuser",params:values}).then(res => {console.log(res)sessionStorage.setItem("token",res.token)sessionStorage.setItem("user",JSON.stringify(res.data[0]))sessionStorage.setItem("power",JSON.stringify(res.power))if(res.code === 200){message.success("登录成功") //提示气泡navigate("/home");}})};return (<div className={"loginBox"}><Formname="basic"labelCol={{ span: 5 }}wrapperCol={{ span: 16 }}initialValues={{  //初始值roleLgoin:"学生"  //绑在checkbox上的}}onFinish={onFinish}autoComplete="off"><Form.Itemlabel="用户名"name="username"rules={[{ required: true, message: '请输入您的用户名!' }]}><Input /></Form.Item><Form.Itemlabel="密码"name="password"rules={[{ required: true, message: '请输入您的密码名!' }]}><Input.Password /></Form.Item><Form.Item name="roleLgoin" label={null}><Radio.Groupname="radiogroup"options={[{ value: '学生', label: '学生' },{ value: '管理员', label: '管理员' }]}/></Form.Item><Form.Item label={null}><Button type="primary" htmlType="submit">Submit</Button></Form.Item></Form></div>)}export default Login;

跨域处理

1.react配置文件暴露弹出来:git add .git commit -m 'msg'npm run eject2.找到配置文件:webpackDevServer.config.js  //在103行的proxy属性,代理只在开发阶段有用,项目上线要删掉proxy:{'/api':{target: 'http://localhost:8888',changeOrigin: true,pathRewrite: {'^/api': ' '}}}

不建议直接暴露文件的不可逆操作,建议使用 craco (create-react-app config)在 React 脚手架的基础上进行 Webpack 配置。具体内容在Webpack\Vite栏中查看

http://www.xdnf.cn/news/126.html

相关文章:

  • ESP32 搭建IDF+Vscode环境(详细教程)
  • 轻量化高精度的视频语义分割
  • 网络安全-Burp Suite基础篇
  • Android 音频架构全解析:从 AudioTrack 到 AudioFlinger
  • 【TeamFlow】 1 TeamFlow 去中心化生产协同系统架构
  • python抓取HTML页面数据+可视化数据分析(投资者数量趋势)
  • NFC 碰一碰发视频源码搭建,碰一碰发视频定制化开发技术
  • JavaScript性能优化实战指南
  • 云轴科技ZStack入选中国人工智能产业发展联盟《大模型应用交付供应商名录》
  • UE5 渲染视频
  • 龙虎榜——20250418
  • 微信小程序中,将搜索组件获取的值传递给父页面(如 index 页面)可以通过 自定义事件 或 页面引用 实现
  • C++面向对象
  • Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
  • Uniapp调用native.js使用经典蓝牙串口通讯方法及问题解决
  • 线上蓝桥杯比赛环境配置
  • MySQL事务详解
  • 【Python语言基础】22、异常处理
  • 【web服务_负载均衡Nginx】二、Nginx 核心技术之负载均衡与反向代理
  • Winform发展历程
  • 【电力安全小知识】什么情况下需要铺设绝缘胶垫
  • AIGC产品如何平衡用户体验与内容安全?
  • HDFS入门】HDFS安全与权限管理解析:从认证到加密的完整指南
  • OpenHarmony-Risc-V上运行openBLAS中的benchmark
  • 部署路线Ubuntu_MySQL_Django_绑定域名
  • 【Python3】Django 学习之路
  • 51单片机实验四:键盘检测原理及应用实现
  • 【科研绘图系列】R语言绘制多个气泡图组合图(bubble plot)
  • MATLAB脚本实现了一个转子系统的参数扫描和分岔分析
  • 华为仓颉智能体开发框架 Cangjie Magic深度解析