我正在制作一个节点项目,尝试将令牌结果用于get请求并在另一个get中使用它时遇到了麻烦。 我该如何使用? 谢谢!
这是我的代码:
app.js
.get('/api/v1/token', tokenController.getToken)
.get('/api/v1/search', searchController.getSearch)
Tokencontroller.js
const eventService = require('../services/eventService')
function getToken(req, res){
eventService.getToken()
.then(response => {
console.log(response.body)
const token = response.body.access
console.log(token)
res.send(token)
})
.catch(error => {
console.log('token error')
next(error)
})
}
module.exports = {getToken}
eventService.js
module.exports = {
getToken() {
return new Promise(function (resolve, reject) {
var payload = {
username: 'jon@mail.com',
password: "1111",
grant_type: 'password',
};
request.post({
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + new Buffer.from('user-one' + ':' + '000000000').toString('base64'),
'Accept': 'application/json'
},
url: 'myurl/oauth/token',
form: payload
}, function (error, response, body) {
if (error) {
reject(error)
} else {
resolve({ response , body })
}
});
})
}
现在我得到了令牌,我需要将其传递给getSearch .. 令牌响应:
{"access_token":"123456","token_type":"bearer","refresh_token":"12345"}
searchController.js
function getSearch(req, res){
eventService.getSearch()
.then(response => {
res.send(response)
})
.catch(error => {
console.log(error)
next(error)
})
}
eventService getSearch
getSearch() {
return new Promise(function (resolve, reject) {
request.post({
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + '123456' //==> token access_token propertie
},
url: 'myurlcontent/search',
}, function (error, response, body) {
if (error) {
reject(error)
} else {
resolve({ response, body })
}
});
})
}