Advantages of the Node forwarding API (Node middle tier)

  • In the Java middle tier | PHP data, processing front end in pairs more friendly format
  • This solves the cross-domain problem on the front end because server-side requests do not involve cross-domain, which is caused by the same origin policy of the browser
  • Multiple requests can be merged through the middle tier to reduce front-end requests
  • API forward: write their own small project, you can take some real data from others to do 😂😂😂
  • .

The Node, Express

Node.js is a JavaScript runtime environment based on Chrome V8 engine. Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient. Express is a fast, open and minimalist Web development framework based on the Node.js platform. Nodemon A plug-in package that implements node hot updates

Quick learning

The document directory

├ ─ ─ dist ├ ─ ─ node_modules ├ ─ ─ public │ └ ─ ─ index. The HTML ├ ─ ─ the SRC │ └ ─ ─ apiList │ ├ ─ ─ index. The js │ └ ─ ─ client_play_list_tag. Js │ └ ─ ─... │ ├─ ├─ ├─ ├─ download.jsonCopy the code

package.json

{
 "name": "testnodeapi"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
   "test": "echo \"Error: no test specified\" && exit 1"."dev": "nodemon src/index.js"
 },
 "author": "alkun"."license": "ISC"."dependencies": {
   "axios": "^ 0.19.0"."express": "^ 4.17.1"
 },
 "devDependencies": {
   "nodemon": "^ 1.19.2"}}Copy the code

Step 1: Configure the entry file index.ts

  1. First, you need to import the downloaded installation package and try to start a service
    const express = require('express')
    const app = express()
    const port = 3001
    app.use((req, res) = > {
        res.send('hahhaha')
    })
    app.listen(port, ()=>{
        console.log('Example app listening on http://127.0.0.1:${port}`)})Copy the code

Step 2: Install Axios and implement a simple forward

. const axios =require('axios')
   
    app.use(async (req, res) => {
        let resp = await axios({
            baseURL: 'http://m.music.migu.cn/migu/remoting/'.method: 'get'.url: '/client_play_list_tag',
        })
        res.send(resp.data)
    })
    
    app.listen(port, () => {
        console.log('Example app listening on http://127.0.0.1:${port]`)})Copy the code

Step 3: We need to do some simple encapsulation of AXIox

// Create a request.js file in the utils folder to process axios
const axios = require('axios')
const userAgent = require('./userAgent')
const request = (paramInfo) = > {
    function getDataFn(obj) {
        let getData = {
            url: obj.url,
            method: obj.method ||'get'.baseURL: 'http://m.music.migu.cn/migu/remoting/'.headers: {
                'User-Agent': userAgent(),
            }
        }
        if (getData.method == 'get'){
            getData.params = obj.data
        } else {
            getData.data = obj.data
        }
        return getData
    }
    
    if(!Array.isArray(paramInfo)){
        return axios(getDataFn(paramInfo))
    } else {
        let fetchArray = paramInfo.map(v= > {
            return axios(getDataFn(v))
        })
        return new Promise((resolve, reject) = > {
            axios.all(fetchArray)
            .then(axios.spread(function (. arg) {
                // Multiple requests are now completed
                resolve(arg)
            })).catch(err= > {
                console.log(err)
            })
        })

    }
}

module.exports = request

Copy the code

Step 4: Create a random User-agent

// Return a random UA that asks for headers
const user_agent_list = [
    // Various PC side
    // Safari
    "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML like Gecko) Version/5.1.7 Safari/534.57.2".// chrome
    "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36"."Mozilla / 5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"."Mozilla / 5.0 (Windows; U; Windows NT 6.1; En-us) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16"./ / 360
    "Mozilla / 5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36"."Mozilla / 5.0 (Windows NT 6.1; WOW64; Trident / 7.0; The rv: 11.0) like Gecko".// QQ browser
    "Mozilla / 5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident / 5.0; SLCC2; The.net CLR 2.0.50727; The.net CLR 3.5.30729; The.net CLR 3.0.30729; Media Center PC 6.0; . NET4.0 C; . NET4.0 E; QQBrowser / 7.0.3698.400)"."Mozilla / 4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; . NET4.0 C; NET4.0 E)".// The sogou browser
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0"."Mozilla / 4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident / 4.0; SV1; QQDownload 732; . NET4.0 C; . NET4.0 E; SE 2. MetaSr 1.0 X)".// Various mobile terminals
    // IPhone
    "Mozilla / 5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; En-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5".// IPod
    "Mozilla / 5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; En-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5".// IPAD
    "Mozilla / 5.0 (the device; U; CPU OS 4_2_1 like Mac OS X; Zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5"."Mozilla / 5.0 (the device; U; CPU OS 4_3_3 like Mac OS X; En-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5".// Android
    "Mozilla / 5.0 (Linux; U; Android 2.2.1. zh-cn; HTC_Wildfire_A3333 Build/FRG83D) AppleWebKit/533.1 (KHTML like Gecko) Version/4.0 Mobile Safari/533.1"."Mozilla / 5.0 (Linux; U; Android 2.3.7. en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1".// QQ browser Android version
    "MQQBrowser / 26 Mozilla / 5.0 (Linux; U; Android 2.3.7. zh-cn; MB200 Build/GRJ22; Cyanogenmod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1".// Android Opera Mobile
    "Opera / 9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; En - GB) Presto / 2.8.149 Version / 11.10".// Android Pad Moto Xoom
    "Mozilla / 5.0 (Linux; U; The Android 3.0. en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13".// BlackBerry
    "Mozilla / 5.0 (BlackBerry; U; BlackBerry 9800; En) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+".// WebOS HP Touchpad
    "Mozilla / 5.0 (HP - tablet; Linux; HpwOS / 3.0.0; U; En-us) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0".// Nokia N97
    "Mozilla / 5.0 (SymbianOS / 9.4; Series60/5.0/20.0.019 NokiaN97-1; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML like Gecko) BrowserNG/7.1.18124".// Windows Phone Mango
    "Mozilla / 5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident / 5.0; IEMobile / 9.0; HTC; Titan)".// UC browser
    "UCWEB7.0.2.37/28/999"."NOKIA5700 UCWEB7.0.2.37/28/999".// UCOpenwave
    "Openwave UCWEB7.0.2.37/28/999".// UC Opera
    "Mozilla / 4.0 (compatible; MSIE 6.0;) Opera/UCWEB7.0.2.37/28/999".// Some PCS
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3"."Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3"."Mozilla / 5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"."Mozilla / 5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]

module.exports = (a)= >{
    let index = Math.floor(Math.random() * user_agent_list.length)
    return user_agent_list[index]
}

Copy the code

Step 5: apiList encapsulation

// Insert the client_play_list_tag.js file under the apiList folder
/** * @api /client_play_list_tag * @param {} */
module.exports = (app) = > {
    app.get('/client_play_list_tag'.async (req, res) => {
        try {
            let result = await app.request({
                url: "client_play_list_tag".data: {
                    ...req.query
                }
            })
            res.send(result.data)
        } catch (err) {
            res.send({ code: - 500..msg: err.message })
        }
    })
}
Copy the code

Step 6: Create the entry file in the current folder./apiList/index.js

const fs = require('fs')
const path = require('path')

const request = require('.. /utils/request')

// Find all API file names in the current folder
const routes = fs.readdirSync(__dirname).filter(item= > item.indexOf('index') != 0)
module.exports = (router) = > {
    // Place the request in each instance
    router.request = request
    routes.forEach((item) = > {
        let routeFn = require(path.resolve(__dirname, item))
        routeFn(router)
    })
    return router
}
Copy the code

Finally: Update our complete entry index.js file

const express = require('express')
const Router = express.Router()

const app = express()

const apiList  = require('./apiList')
const port = 3001
app.use((req, res, next) => {
    res.set('Access-Control-Allow-Origin'.The '*'App.use (apiList(Router)) app.listen(port) () => {console.log(' Example app listening on http://127.0.0.1:${port}`)})Copy the code

At this point, this article has basically implemented the music API forwarding function, there are some other interfaces, you need to go to

Note:

The code covered in this article is still very simple, and more sophisticated features will need to be dealt with yourself. TS + Node + Express welcome STAR STAR STAR portal