react5.0中axios中的封装使用以及dev代理

react5.0中axios中的封装使用以及dev代理

  • 1. 封装在src/utils/axios
  • 2. 封装service在src/service/login/login.js
  • 3. 在react中使用service在src/pages/login/index.tsx
  • 4. 配置baseURL,代理自动跨域

1. 封装在src/utils/axios

封装在src/utils/axios

import axios from 'axios'

let httpService = axios.create({
  baseURL: process.env.REACT_APP_URL,
  timeout: 5000
})

// 拦截请求
httpService.interceptors.request.use(config => {
  if (localStorage.getItem('token')) {
    config.headers.token = localStorage.getItem('token');
  }
  return config;
},err => {
  Promise.reject(err);
})

// 拦截响应
httpService.interceptors.response.use(response => {
  return response.data.data;
},err => {
  return Promise.reject(err);
})

// get请求的封装
export async function  get(url, params={}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method: 'get',
      params: params,
      headers: headers,
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

// post请求封装 
export async function post(url, data = {}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method:'post',
      data: JSON.stringify(data),
      headers: headers
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

// put请求封装 
export async function put(url, data = {}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method:'put',
      data: JSON.stringify(data),
      headers: headers
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

// delete请求的封装
export async function deleteMethod(url, data={}, headers = {'Content-Type':'application/json'}) {
  return new Promise((resolve,reject) => {
    httpService({
      url: url,
      method: 'delete',
      data: JSON.stringify(data),
      headers: headers,
    }).then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    })
  })
}

2. 封装service在src/service/login/login.js

import { post} from '../../utils/axios.js'

export async function loginService(data) {
  return post(
    'user/login',
    data,
  )
}

3. 在react中使用service在src/pages/login/index.tsx

import React, { useState } from 'react';
import { Button, Form, Input } from 'antd';
import { loginService} from '../../service/login/login.js';

const LoginForm: React.FC = props => {

  const [user] = useState({
    userId: 'admin',
    password: 'admin',
  });

  const onFinish = async (values: any) => {
    const data = await loginService(values)
    localStorage.setItem('token', data);
  }
  
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div id='loginForm'>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={ user }
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="账号"
          name="userId"
          rules={[{ required: true, message: '请输入账号!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default LoginForm;

4. 配置baseURL,代理自动跨域

.env.development

ENV = 'development'
REACT_APP_URL = 'http://localhost:8082'

你可能感兴趣的:(框架集成,javascript,前端,react.js)