首页 > 解决方案 > 如何从 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))
 });
})

标签: node.jsaxiosmocha.js

解决方案


您可以将其包装在 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)
    }
}

快速示例


推荐阅读