Axios请求与redux

Axios请求与redux全局

平台搭建

解压

开启命令行,安装依赖包

npm i

数据库的导入

调整数据库配置

测试

http://localhost:3001/api/getgoods

跨域

定义:可在前面博客查询

token原理:项目介绍、接口文档、JWT的使用_爱敲代码的狼仔的博客-CSDN博客

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说 Web 是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。它的核心就在于它认为自任何站点装载的信赖内容是不安全的。当被浏览器半信半疑的脚本运行在沙箱时,它们应该只被允许访问来自同一站点的资源,而不是那些来自其它站点可能怀有恶意的资源。所谓同源是指:域名、协议、端口相同。

react脚手架的两种跨域:跨越、以及解决跨越调用的办法_爱敲代码的狼仔的博客-CSDN博客

跨域问题

方式一

通过package.json跨域

方法二

方法一已经实现了跨域,但是,不够灵活,只能全局设置一个跨域地址。

可以借助三方的插件http-proxy-middleware灵活跨域

npm i http-proxy-middleware -D
npm install --save-dev http-proxy-middleware

配置跨域的文件需要在src目录下创建setupProxy.js文件,写法固定

const createProxyMiddleware  = require('http-proxy-middleware');
module.exports = function(app){
        app.use(createProxyMiddleware('/api',{
            target: 'http://127.0.0.1:3001' 
        })       
    )
}

axios

安装

npm i axios -S

axios({
    url: "url",
    method: "post",
    headers: {},
    data: {}
}).then(res=>{
​
}).catch(error=>{
​
})

get

axios.get('http://localhost:3001/api/getgoods',{headers:{},params:{}}).then(res=>{
    console.log(res)
}).catch(error=>{
    console.log(error)
})

POST

axios.post('http://localhost:3001/api/getgoods',headers:{},data:{}).then(res=>{
    console.log(res)
}).catch(error=>{
    console.log(error)
})
axios.post(url).then(res=>{})

封装

import axios from "axios";
import {Component} from "react";

// axios.defaults.baseURL = "/api"

axios.interceptors.response.use(response=>{
    return response.data
})

Component.prototype.$http = axios

export default axios

fetch

类似axios

fetch是高级浏览器内置的一个发送数据请求的API >IE8.0

fetch底层基于Promise

fetch依然会受到同源策略的限制

GET

var url = '/api/getgoods'
fetch(url).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)

fetch默认式get请求,所以请求头设置部分可以省略,完整写法如下

var url = '/api/getgoods'
fetch(url,{
    method: "GET",
    headers: {}
}).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)

POST

var url = '/api/getgoods'
fetch(url,{
    method: "POST",
    headers: {
        'Content-Type': "application/json"
    },
    body: JSON.stringify({
        username: "root",
        password: "123"
    }),
}).then(
    res=>{
        return res.json()//当前步骤只是接受到了响应对象,不能在这里看到响应数据
    }
).then(
    res=>{
        console.log(res,"++++++++++++++++++++++++++++")
    }
)

封装

封装代码

export function request(url,method="GET",body={},headers={}){
    const option = {
        method,
        headers: Object.assign({"Content-Type": "application/json"},headers)//合并对象,设置默认头
    }
    if(method === "POST"){
        option.body = JSON.stringify(body)
    }
    return fetch(url,option).then(response=>{
        return response.json()
    })
}

使用

React全局数据控制(redux)

redux是一个react的状态管理工具, 作用就是帮助我们管理一些需要在组件之间进行共享的数据

下载

npm i redux -S

基本结构

import {createStore} from 'redux'
const init_list = [
    {
        id:3,
        name: "张三",
        age: 18
    },
    {
        id:2,
        name: "李四",
        age: 18
    },
    {
        id:1,
        name: "王五",
        age: 18
    }
]
function personList(state = init_list,action){
    switch (action.type){
        case 'insert':
            console.log("这里是插入")
            break
        case 'delete':
            console.log("这里是删除")
            break
        case 'update':
            console.log("这里是修改")
            break
        case 'select':
            console.log("这里是条件查询")   
            break 
        default:
            return state
    }
}
const store = createStore(personList) //创建一个store对象
export default store

store对象

常用方法

getState 获取store当中的数据
dispatch 传入剧本,调用store封装的函数的指定部分

基本操作

完成案例

列表数据的增删改查

定义格式

npm i antd -S

import React, { Component } from 'react'
import store from '../redux'
import { Table, Input } from 'antd';
import '../asserts/css/layout.css'
export default class Layout extends Component {
    state = {
        dataSource: [],
        columns: [
            {
                title: '编号', //表头字段
                dataIndex: 'id', //调用数据对应的字段 table.id
            },
            {
                title: '姓名',
                dataIndex: 'name',

            },
            {
                title: '年龄',
                dataIndex: 'age',

            },
        ]
    }
    UNSAFE_componentWillMount() {
        this.setState({
            dataSource: store.getState()
        });
    }
    render() {
        return (
            <>
                <div class="yangshi">
                    <Input placeholder="Basic usage" />
                    <Table 
                       dataSource={this.state.dataSource} 
                       columns={this.state.columns} 
                    />
                </div>
            </>
        )
    }
}

1、 不能多次返回同一个对象,在reduser当中,不可以返回原生的state

2、store.getState()获取的reduser返回的数据,但是当指向dispatch之后,获取的是dispatch修改的数据

代码如下:

reducer代码

redux/index.js

import {createStore} from 'redux'
const init_list = [
    {
        id:3,
        name: "张三",
        age: 18
    },
    {
        id:2,
        name: "李四",
        age: 18
    },
    {
        id:1,
        name: "王五",
        age: 18
    }
]
function personList(state = init_list,action){
    switch (action.type){
        case 'insert':
            var id = state.length>0?state[0].id+1:1
            let {name,age} = action.data
            var obj = {
                id: id,
                name:name,
                age:age
            }
            return [obj,...state] 
            //不能多次返回同一个对象,在reduser当中,不可以返回原生的state
        case 'delete':
            console.log("这里是删除")
            break
        case 'update':
            console.log("这里是修改")
            break
        default:
            return state
    } 
}
const store = createStore(personList) //创建一个store对象
export default store

layout.jsx

import React, { Component } from 'react'
import store from '../redux'
import { Table, Input,Form,Button } from 'antd';
import '../asserts/css/layout.css'
export default class Layout extends Component {
    state = {
        dataSource: [],
        columns: [
            {
                title: '编号', //表头字段
                dataIndex: 'id', //调用数据对应的字段 table.id
            },
            {
                title: '姓名',
                dataIndex: 'name',

            },
            {
                title: '年龄',
                dataIndex: 'age',

            },
        ]
    }
    UNSAFE_componentWillMount() {
        this.setState({
            dataSource: store.getState()
        });
    }
    submit(value){
        store.dispatch({
            type: 'insert',
            data: value
        })
        this.setState({
            dataSource: store.getState()
        });
    }
    render() {
        return (
            <>
                <div className="yangshi">
                    <Form
                        name="basic"
                        labelCol={
   
   { span: 8 }}
                        wrapperCol={
   
   { span: 16 }}
                        initialValues={
   
   { remember: true }}
                        autoComplete="off"
                        onFinish={this.submit.bind(this)}
                    >
                        <Form.Item
                            label="用户名"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="年龄"
                            name="age"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item wrapperCol={
   
   { offset: 8, span: 16 }}>
                            <Button type="primary" htmlType="submit">
                                保存
                            </Button>
                        </Form.Item>
                    </Form>

                    <Table 
                       dataSource={this.state.dataSource} 
                       columns={this.state.columns} 
                    />
                </div>
            </>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/qq_48469083/article/details/121338766
今日推荐