【问题标题】:Capture a Response from GET and Use it in the Next Request从 GET 捕获响应并在下一个请求中使用它
【发布时间】:2019-06-24 21:57:40
【问题描述】:

我正在尝试使用axios.get 的响应,并在axios.post 中使用它。如何将响应用作 POST 请求中的标头?

我尝试在请求配置中使用axios.postheaders

var config = {
  headers: {
    'Access-Control-Allow-Origin': '*',
    'user': newUser.eid,
    'pass':'bd957c3fbb'
  }
}

/*
const axios = require('axios')

getCrumb() {
  return axios.get('https://jenkins.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)', config)
  .then(response => {
    return response
  })
}
*/


/* code to get jenkins crumb */
const getJenkinsCrumb = () => {
  try {
    return axios.get('https://jenkins.com/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)', config)
      .then((crumbValue) => {
        console.log(crumbValue.data);
      })
  } catch (error) {
    console.log(error)
  }
}
getJenkinsCrumb();

我想使用上一个GET 请求(上)的响应作为POST 调用(下)中的标头。

var crumbHeader = {
  headers: {
    'Access-Control-Allow-Origin': '*',
  }
}

/* post api to kick off the build */

try {
  return axios.post('https://abc123:bd95701859@jenkins.com/job/Non- PAR/job/Non-Prod-Jobs/job/uitest/job/TestJob/buildWithParameters?nodes=100000&clustername=clustername', crumbHeader)
    .then((postKickTest) =>{
      console.log(postKickTest.data);
    })
} catch (error) {
  console.log(error)
}

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    Axios request config 包含一个 headers 属性来指定请求的标头。配置可以指定为axios.post() 的第二个参数(如果使用二参数签名)或第三个参数(如果使用三参数签名)。此示例演示了 axios.post() 的两个参数签名,它将 headers 设置为先前请求的数据结果:

    export default {
      methods: {
        async sendRequest() {
          const userResp = await axios.get('https://reqres.in/api/users/2')
          await axios.post('https://reqres.in/api/users', {
            headers: userResp.data,
            data: {
              name: 'john doe',
              job: 'leader',
            }
          })
        },
      }
    }
    

    demo


    旁注:Access-Control-Allow-Origin 是一个 CORS 标头,只能由服务器设置。从客户端发送时无效。您可能错误地认为标头没有到达服务器,因为它没有解决 CORS 问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多