• ArthurSlog

  • SLog-99

  • 1 Year,

  • Through China,

  • October 20th 2018

Scan the QR code on wechat and follow my official account

  • Personal website: http://www.arthurslog.com

  • CSDN:https://blog.csdn.net/u010997452/article/list/1

  • GitHub:https://github.com/BlessedChild/ArthurSlog

  • NPM:https://www.npmjs.com/~arthurslog

  • The Denver nuggets: https://juejin.cn/user/307518986009559

  • Jane: https://www.jianshu.com/u/b9ebe10f0534

  • segmentfault:https://segmentfault.com/u/arthurslog/articles

My words are easy to know and easy to do


Development Environment MacOS(Mojave 10.14 (18A391))

Information sources

  • Ajax

  • Fetch

Start coding

  • This time to achieve the front-end and back-end interface design

  • The native Fetch function is used here

  • Start by adding a function to the front page that binds the page component’s click event to the back end for making requests and passing data

  • Add here the click event that binds to the ‘announcements’ component on the mall home page

client/

import React, { Component } from 'react'

import Carouselarea from './carouselarea/carouselarea'

// Import the configuration file
import Config from '.. /.. /.. /.. /config.json'

const bulletinBoardStyle = { alignItems: 'center'.display: 'flex'.flexDirection: 'raw'.width: '100%'.height: 64.fontSize: 40.textAlign: 'center'.borderStyle: 'none' }
const productListStyle = { width: '100%'.fontSize: 40.textAlign: 'center' }
const dividingLineStyle = { backgroundColor: '# 000000'.height: 1.width: '100%' }
const recommendStyle = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#FFFFFF'.width: '100%' }
const navigationBarStyle = { display: 'flex'.alignItems: 'stretch'.backgroundColor: '#FFFFFF' }
const navigationBarItemStyle = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '25%'.marginLeft: '10px'.marginRight: '10px'.textAlign: 'center'.fontSize: '30' }
const navigationBarItemStyleLeft = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '25%'.marginLeft: '20px'.marginRight: '10px'.textAlign: 'center'.fontSize: '30' }
const navigationBarItemStyleLRight = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '25%'.marginLeft: '10px'.marginRight: '20px'.textAlign: 'center'.fontSize: '30' }
const categoryStyle = { display: 'flex'.alignItems: 'stretch'.backgroundColor: '#FFFFFF' }
const categoryItemStyle = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '33.3%'.marginLeft: '10px'.marginRight: '10px'.textAlign: 'center'.fontSize: '30' }
const categoryItemStyleLeft = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '33.3%'.marginLeft: '20px'.marginRight: '10px'.textAlign: 'center'.fontSize: '30' }
const categoryItemStyleLRight = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '33.3%'.marginLeft: '10px'.marginRight: '20px'.textAlign: 'center'.fontSize: '30' }
const categoryImgItemStyleLeft = { width: '220px'.height: '220px'.textAlign: 'center'.lineHeight: '220px'.backgroundColor: '#FFFFFF' }
const productStyle = { display: 'flex'.alignItems: 'stretch'.backgroundColor: '#FFFFFF' }
// const productItemStyle = { alignItems: 'center', display: 'flex', flexDirection: 'column', backgroundColor: '# d8f0F3 ', color: '#000000', width: '33.3%', marginLeft: '10px', marginRight: '10px', textAlign: 'center', fontSize: '30'}
const productItemStyleLeft = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '50%'.marginLeft: '20px'.marginRight: '10px'.textAlign: 'center'.fontSize: '30' }
const productItemStyleRight = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.color: '# 000000'.width: '50%'.marginLeft: '10px'.marginRight: '20px'.textAlign: 'center'.fontSize: '30' }
const productImgItemStyle = { width: '400px'.height: '400px'.textAlign: 'center'.lineHeight: '400px'.backgroundColor: '#FFFFFF' }

const productItemInfoTextStyle = { width: '400px'.marginLeft: '0px'.textAlign: 'left' }
const productItemInfoPriceStyle = { width: '400px'.marginLeft: '0px'.textAlign: 'left' }
const productItemInfoStyle = { alignItems: 'center'.display: 'flex'.flexDirection: 'column'.backgroundColor: '#d8f0f3'.width: '400px' }
const productItemInfoTextareaStyle = { width: '400px'.textAlign: 'left'.margin: '0px' }

const bulletinBoardIconStyle = { width: '56px'.height: '56px'.fontSize: '12px'.textAlign: 'center'.lineHeight: '56px'.marginLeft: '20px' }
const recommendIconStyle = { width: '256px'.height: '256px'.textAlign: 'center'.lineHeight: '256px'.borderStyle: 'solid' }


const navigationBarIconItemStyle = { width: '200px'.height: '200px'.textAlign: 'center'.lineHeight: '200px'.backgroundColor: '#FFFFFF'.borderStyle: 'solid' }

// The BodyContainet area style
// const bodyContainerBarStyle = { position: "relative", marginTop: 0, marginBottom: 128, height: '100%', width: '100%'}

// Render the content of the BodyContainer area
class BodyContainer extends Component {

    render() {
        return <div>
            <Carouselarea />
            <div>
                <div style={dividingLineStyle}></div>
                <div style={bulletinBoardStyle} onClick={this.toucha}>
                    <div style={bulletinBoardIconStyle} >The picture</div>
                    <div className='bulletinBoard'>bulletinBoard</div>
                </div>
                <div style={dividingLineStyle}></div>
            </div>
            <div className='navigationBar' style={navigationBarStyle}>
                <div style={navigationBarItemStyleLeft}>
                    <div style={navigationBarIconItemStyle}>The picture</div>
                    <div>All the goods</div>
                </div>
                <div style={navigationBarItemStyle}>
                    <div style={navigationBarIconItemStyle}>The picture</div>
                    <div>Spell group</div>
                </div>
                <div style={navigationBarItemStyle}>
                    <div style={navigationBarIconItemStyle}>The picture</div>
                    <div>Timed promotions</div>
                </div>
                <div style={navigationBarItemStyleLRight}>
                    <div style={navigationBarIconItemStyle}>The picture</div>
                    <div>Seconds kill</div>
                </div>
            </div>
            <div style={dividingLineStyle}></div>
            <div className='recommend' style={recommendStyle}>
                <div style={recommendIconStyle}>The picture</div>
                <div>Recommend sell like hot cakes</div>
            </div>
            <div style={dividingLineStyle}></div>
            <div className='category'>
                <div style={categoryStyle}>
                    <div style={categoryItemStyleLeft}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 1</div>
                    </div>
                    <div style={categoryItemStyle}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 2</div>
                    </div>
                    <div style={categoryItemStyleLRight}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 3</div>
                    </div>
                </div>
                <div style={categoryStyle}>
                    <div style={categoryItemStyleLeft}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 4</div>
                    </div>
                    <div style={categoryItemStyle}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 5</div>
                    </div>
                    <div style={categoryItemStyleLRight}>
                        <div style={categoryImgItemStyleLeft}>The picture</div>
                        <div>Category 6</div>
                    </div>
                </div>
            </div>
            <div style={dividingLineStyle}></div>
            <div className='productList' style={productListStyle}>
                <div style={productStyle}>
                    <div style={productItemStyleLeft}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                    <div style={productItemStyleRight}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div style={productStyle}>
                    <div style={productItemStyleLeft}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                    <div style={productItemStyleRight}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div style={productStyle}>
                    <div style={productItemStyleLeft}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                    <div style={productItemStyleRight}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                </div>
                <div style={productStyle}>
                    <div style={productItemStyleLeft}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                    <div style={productItemStyleRight}>
                        <div style={productImgItemStyle}>The picture</div>
                        <div style={productItemInfoStyle}>
                            <div style={productItemInfoTextStyle}>The introduction</div>
                            <div style={productItemInfoPriceStyle}>
                                <span style={productItemInfoTextareaStyle}>selections</span>
                                <span style={productItemInfoTextareaStyle}>8888</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div style={{ marginBottom: '256px' }}></div>
        </div>
    }


    toucha() {
        const myObj = { func: 0.object: "test" }
        fetch(Config.baseUrl + 'api/client', {
            method: 'POST'.headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(myObj),
        })
            .then(response= > {
                console.log('Add data to message successfuly')
                const resmsg = response.json()
                console.log('Response1: ', resmsg)
                console.log('Response2: ', response)
                return resmsg
            })
            .catch(err= > {
                alert("Error in sending data to server: " + err.message)
            })
    }
}

export default BodyContainer
Copy the code
  • Well, the code is a little long and hasn’t been cleaned and optimized

  • But you can see the key part here

. // Import Config from '.. /.. /.. /.. /config.json' ... . <div style={bulletinBoardStyle} onClick={this.toucha}> <div style={bulletinBoardIconStyle} > picture </div> <div ClassName ='bulletinBoard'>bulletinBoard </div> </div>... . toucha() { const myObj = { func: 0, object: "test" } fetch(Config.baseUrl + 'api/client', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(myObj), }) .then(response => { console.log('Add data to message successfuly') const resmsg = response.json() console.log('Response1: ', resmsg) console.log('Response2: ', response) return resmsg }) .catch(err => { alert("Error in sending data to server: " + err.message) }) } ...Copy the code
  • The back-end address is defined in the external file config.json

  • Then bind click events on the ‘bulletin board’ component of ‘mall home page’

  • The event is associated with the Toucha function, which makes a request to the server

  • The request is made with two pieces of data one is’ func: 0 ‘and the other is’ object: “test”.

  • Func represents the code of the function function and the back end uses the value of func passed by the front end to determine what the front end is currently trying to do and what function is it trying to execute

  • Object is the data that gets passed from the front end to the back end and then processed by the back end and then what you do with it depends on how you design it when you develop it, okay

  • Here is the code for the back end

// This function receives data from the client
// Check whether the data contains the bootomTabBar value
// Return data for each base interface based on the values of the four BootomTabBars
// The following is an example
// For example, this function receives a data data which contains the data 'count' and 'tabBar'.
// And 'count' = 1 and 'tabBar' = 1
// This represents the number of bootomTabbars the client wants to get.
// So through this function
// The client can request the data of the first interface, the data of the second interface, the data of the third interface and the data of the fourth interface
/ / {
// count: int, // This represents the number of bootomTabbars to be modified
// tabBar: [] // This is bootomTabBar
// }
//
// There is another way that all methods can be unified into one function
All ('/ API /POST',...
// How to determine which function is requested by the client?
// This is done by checking the specific fields in the data sent by the client
// The route is routed according to the value of 'func' in the data sent by the client
// Route what? Route to the specified function
// For example, 'func' ==01 in data from client
// Then route to function func1 which returns the data of the first interface
/ / if 'func = =' 02
// Then route to function func2, which returns data for the second interface
// And so on
// To do so requires rigorous checks on the back end and an industrial-level mechanism
// This is a bit like writing an underlying protocol
// The header + the body mode
//
// The data structure passed by the client
/ / {
// func: int, //
// object: [] //
// }
app.all('/api/client', (req, res) => {
    console.log(req.body)
    // Receive data from the client
    /* const newDatas = req.body // if ((newdatas.count! = 0) && (newDatas.count < 5)) { console.log('Accept: ', newDatas) // newIssue.id = issues.length + 1 newIssue.created = new Date() if (! newIssue.status) newIssue.status = 'New' // issues.push(newIssue) const err = Issue.validIssueStatus(newIssue) if (err) { res.status(422).json({ message: `Invalid request: ${err}` }) return } if (! newIssue) { console.log('newIssue is null') } else if (newIssue) { db.collection('issues').insertOne(newIssue) .then(result => { return db.collection('issues').find({ _id: result.insertedId }).limit(1).next() }) .then(newIssue => { if (newIssue) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type") res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") res.header("X-Powered-By", '3.2.1) res. The header (" the content-type ", "application/json. charset=utf-8") res.json(newIssue) } else { console.log('newIssue is null') return } }) .catch(err => { console.log(err)  res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type") res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") res.header("X-Powered-By", '3.2.1) res. The header (" the content-type ", "application/json. charset=utf-8") res.status(500).json({ message: `Internal Server Error: ${err} '}) console.log('newIssue is error')})}} else {// If the received data does not match the expected res.header(" access-Control-allow-Origin ", "*") res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type") res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") res.header("X-Powered-By", '3.2.1) res. The header (" the content-type ", "application/json. charset=utf-8") res.json(newIssue) console.log('Client request is err! ') return } console.log('POST: have a req from client') */

    // Now use the second method
    // The data is first received from the client and stored in the recDatas object
    const recDatas = req.body
    // Then we agree on the data structure is the packet header + packet body
    // Data structures such as func + object
    // So first determine the value of func and then execute different functions based on different values
    switch (recDatas.func) {
        case 0:
            console.log('Received data with func = 0')
            res.header("Access-Control-Allow-Origin"."*")
            res.header("Access-Control-Allow-Headers"."X-Requested-With, Content-Type")
            res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS")
            res.header("X-Powered-By".'3.2.1')
            res.header("Content-Type"."application/json; charset=utf-8")
            // Here we pass object to function for processing and we also need to pass res to function for feedback to client
            const results = Func1.func1(recDatas.object)
            res.json(results)
            console.log(results)
            break;
        case 1:
            Func1(recDatas.object, res);
            break;
        case 2:
            Func1(recDatas.object, res);
            break;
        case 3:
            Func1(recDatas.object, res);
            break;
        case 4:
            Func1(recDatas.object, res);
            break;
        case 5:
            Func1(recDatas.object, res);
            break;
        case 6:
            Func1(recDatas.object, res);
        default:
            res.header("Access-Control-Allow-Origin"."*")
            res.header("Access-Control-Allow-Headers"."X-Requested-With, Content-Type")
            res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS")
            res.header("X-Powered-By".'3.2.1')
            res.header("Content-Type"."application/json; charset=utf-8")
            res.json('error'); }})Copy the code
  • There are some syntax problems with the syntax in switch

  • The key is to look at the comments

  • The content of the annotations explains the logical design of a business

  • Finally, after the test, data interaction was successfully realized at the front and back ends

  • So the key idea here has been presented and it’s a good idea not to talk too much about it

  • Project files have been uploaded to Github:https://github.com/BlessedChild/ArthurSlogStore

  • At this point, the design of the business logic for data interaction between the front and back ends is determined.


  • Please follow my wechat account ArthurSlog
Scan the QR code on wechat and follow my official account

  • If you like my article, please like it and leave a comment

  • thank you