uniapp.request请求头带上token
时间: 2023-09-27 21:11:49 浏览: 241
要在uniapp.request请求头中携带token,可以按照以下步骤进行操作:
1. 打开main.js文件并导入$request。在main.js文件中,通过引用import {request} from './utils/request.js'将$request引入到项目中。
2. 在utils/request.js文件中找到request方法。在这个方法中,我们可以看到在发送请求前会检查是否存在token。如果存在token,就会将其添加到请求头中的Authorization字段。
3. 在登录成功后,将token存储在uni.setStorageSync("token", res.data)中。
通过以上步骤,uniapp.request请求将会自动在请求头中带上token。
相关问题
uni.request请求头加不上
如果你使用uni.request请求时,请求头没有被正确添加,你可以尝试以下方法:
1. 在请求的options中设置header参数,例如:
```
uni.request({
url: 'https://example.com',
method: 'GET',
header: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
success: function (res) {
console.log(res);
}
});
```
2. 在项目的config.js中设置公共的请求头,例如:
```
export default {
baseUrl: 'https://example.com',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
}
```
然后在请求时引入config.js中的headers,例如:
```
import config from '@/config.js';
uni.request({
url: config.baseUrl + '/users',
method: 'GET',
header: config.headers,
success: function (res) {
console.log(res);
}
});
```
希望以上方法能帮到你解决问题。
uniapp发送get请求并且携带token
可以使用uni.request()方法发送get请求,并在header中携带token。具体代码如下:
uni.request({
url: 'http://example.com/api',
method: 'GET',
header: {
'Authorization': 'Bearer ' + token
},
success: function(res) {
console.log(res.data);
},
fail: function(err) {
console.log(err);
}
});