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

【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栏中查看

相关文章:

  • string函数的应用
  • 基于 BaseRecyclerViewAdapterHelper 4.x 的封装
  • PyTorch快速入门
  • ETL数据集成平台在交通运输行业的五大应用场景
  • 文件包含(详解)
  • 全志H5,NanopiKP1lus移植QT5.12记录
  • 常用的优化算法及横向对比
  • langchain tools源码解析以及扩展
  • 快速使用工具Cursor
  • 【天外之物】线元
  • MacOS怎么显示隐藏文件
  • python-图片分割
  • 慢速率拉伸热变形工艺试验机
  • 通俗理解MCP(Model Context Protocol)和A2A(Agent2Agent)
  • kaamel Privacy agent:AI赋能的隐私保护技术解决方案
  • [特殊字符] 当Docker遇上大模型:本地运行LLM的奇幻漂流 [特殊字符]
  • 68.评论日记
  • 使用dompurify修复XSS跨站脚本缺陷
  • ABAP OLE
  • 一次制作参考网杂志的阅读书源的实操经验总结(附书源)
  • 人民日报刊文:美国滥施关税及中国反制措施的法理视角透析
  • 智慧菜场团标试验:标准化的同时还能保留个性化吗?
  • 北京:义务教育阶段入学将积极为多孩家庭长幼随学创造条件
  • 两部门通报18个破坏耕地、毁林毁草典型问题
  • 浙江、安徽公布一季度外贸数据,出口增速均达到两位数
  • 救命,每次坐飞机都头疼到炸?快看这篇