Home >Web Front-end >uni-app >How to set request header in uniapp
When developing using uniapp recently, sometimes it is necessary to set request header information in the request so that the server can process the request correctly. Let’s share how to set request headers in uniapp.
You can set the request header information globally in the project's main.js
, so that in any request will carry this information. The specific method is as follows:
import Vue from 'vue' import App from './App' Vue.config.productionTip = false Vue.prototype.$http = function(url, method, data){ return new Promise((resolve, reject) => { uni.request({ url: 'http://localhost:8080/' + url, method: method, data: data, header:{ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + uni.getStorageSync('token') }, success: (res) => { resolve(res); }, fail: (res) => { reject(res); } }); }); } App.mpType = 'app' const app = new Vue({ ...App }) app.$mount()
In the above code, header
is the request header information that needs to be set, where Content-Type
represents the type of request data, Authorization
represents the user's access token, which can be modified according to the actual situation.
Sometimes, we may need to set a certain request header information in a single request. At this time, we can set the header
in the uni.request
method. The sample code is as follows:
uni.request({ url: 'http://localhost:8080/' + url, method: method, data: data, header:{ 'Authorization': 'Bearer ' + uni.getStorageSync('token') }, success: (res) => { resolve(res); }, fail: (res) => { reject(res); } });
When using request headers, you need to pay attention to the following points:
Through the above introduction, I believe everyone already understands the method of setting request headers in uniapp. In actual development, setting according to your actual needs can improve the interactive experience and data security.
The above is the detailed content of How to set request header in uniapp. For more information, please follow other related articles on the PHP Chinese website!