node.js - 如何从 axios post API 请求中获取特定字段
问题描述
我正在使用下面的代码
const axios = require('axios')
axios
.post('https://xxx', {
"audience": "http://xxxx",
"grant_type": "xxxxx",
"client_id": "xxxxx",
"client_secret": "xxxxx"
})
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
})
我想将“res.data.token”分配给变量令牌并在下面的代码中使用该变量
describe('/GET device information', function () {
it("it should GET a Good Auth Status", function(done) {
chai.request('http:xxxxxx')
.get('xxxxxxxxxxxx')
.set({ "Authorization": `Bearer ${token}` })
.then((res) => {
(res).should.have.status(200);
// console.log(body) - not really needed, but I include them as a comment
done();
}).catch((err) => done(err))
});
})
解决方案
您可以将其包装在 try/catch 中并解构对象:
try {
const res = await axios.post('https://xxx', {
'audience': 'http://xxxx',
'grant_type': 'xxxxx',
'client_id': 'xxxxx',
'client_secret': 'xxxxx'
})
const { data, token, foo, bar, status } = res.data
(status).should.equal(200)
} catch(e) {
console.log(e)
}
}
快速示例
推荐阅读
- html - yajra 数据表在移动视图中响应表外
- flutter - 垂直滚动+上下效果
- java - 入站通道适配器 - 基于 Java / 注释的配置以使用控制总线启动/停止
- c# - Linq 语句有 10 个错误
- node.js - 在heroku上部署后反应网络错误
- javascript - 为轮播绘制一行内容
- oracle - 调用用户定义的异常,但是当引发其他异常时
- mysql - 计算 MySQL 中的最新 dup 值
- pytorch - 有没有办法计算两个二维数组彼此之间的差异?
- php - 您如何在 Google Cloud Vision(PHP SDK)中向 ImageAnnotatorClient 进行身份验证(或传递身份验证文件)