- 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欄中查看