How to judge the server type in front end / UNI app?

Time:2021-7-20

GitHub address

Recently passedwebsocketIn the process of developing customer service chat function, the back-end studentsApacheServer reverse proxy reason, need to be inNginxServer and ApachewebsocketYou need to add an identification after connecting the interface.

But the judgment of the server needs to be made by the front end. At this time, we can see the return header of the daily request interface in the browser
Response HeadersYou can see a key calledServer

How to judge the server type in front end / UNI app?

But the front end wants to getResponse HeadersThe corresponding fields in need of background configuration to get

first

The permissions of the headers field that can be obtained by the back end in the configuration front end are as follows:

'Access-Control-Expose-Headers' => 'Server'

In this way, the front-end students can get the corresponding fields in the request request (the method of getting the fields is in the uniapp and PC side)

Method of getting server type by uni app

uni.request({
    url: Url + '/api/' + url,
    method: method || 'GET',
    header: header,
    complete: (data) => {
        // #ifdef H5 || APP-PLUS
        uni.setStorageSync('SERVER_TYPE', data.header.server);
        //  #endif
        // #ifdef MP
        uni.setStorageSync('SERVER_TYPE', data.header.Server);
        // #endif
        }
    },
})
be careful

There is a pit in the official account of H5.serverCan be obtained normally, but in theMP(wechat applet) must be capitalizedServerWe need to pay attention to it

The method of acquiring PC

//Response interceptor
service.interceptors.response.use(
    response => {
        //Get server type
        sessionStorage.setItem("SERVER_ TYPE", response.headers['server']);  // Whether the request here needs to be capitalized on the mobile terminal needs to be tried by you
       
    }
);

If buddy shopping mall needs to learn the development of the mall, it can pay attention to my official account.With the youthsearchSource codeorMall source code