簡體   English   中英

Vue JS 中 axios 的 Slack API CORS 錯誤

[英]Slack API CORS error with axios in Vue JS

我正在使用 Capacitor JS 和 Nuxt JS 構建一個應用程序來與 Slack API 交互,以便我可以設置我的 Slack 狀態,我已經創建了一個 Slack 應用程序並有一個xoxp-令牌,當我點擊端點時它可以正常工作通過 Postman 發出POST請求,但從我的瀏覽器(本地主機)和手機上正在運行的應用程序中,我收到以下 CORS 錯誤:

從源“http://localhost:3000”訪問“https://slack.com/api/users.profile.set”的 XMLHttpRequest 已被 CORS 策略阻止:訪問控制不允許請求標頭字段授權- 預檢響應中的允許標題。

現在這看起來很愚蠢,因為您必須使用authorization標頭來提供用於身份驗證的承載令牌,但即使暫時省略了這一點,CORS 錯誤仍然存​​在。

我正在嘗試POSTusers.profile.set的端點查看另一種方法

我的 Axios 代碼中缺少什么?

setSlackStatusWithReminder (title, expiry) {
  const body = this.convertToQueryString({
    profile: this.convertToQueryString(this.profile),
    token: 'xoxp-mytoken'
  })

  this.$axios.post('https://slack.com/api/users.profile.set', body, {
    timeout: 10000,
    transformRequest(data, headers) {
      delete headers.common['Content-Type'];
      return data;
    }
  }).then(res => {
    console.log(res)

    if (res.data.ok != true) {
      alert('something went wrong with the .then')
    }

    this.isSettingStatus = false
    this.actions.isShown = false
  }).catch(err => {
    this.isSettingStatus = false
    this.actions.isShown = false
  })
},

更新

我有一個函數可以將我的請求正文轉換為我的數據中的查詢字符串,如下所示:

export default {
  data () {
    return {
      profile: {
        status_text: '',
        status_emoji: '',
        status_expiration: 0
      }
    }
  }
}

查詢字符串函數轉換正文

convertToQueryString (obj) {
  const convert = Object.keys(obj)
                         .map((key, index) => `${key}=${encodeURIComponent(obj[key])}`)
                         .join('&')

  return convert
},

我正在構建它:

const body = this.convertToQueryString({
        profile: this.convertToQueryString(this.profile),
        token: 'xoxp-mytoken'
      })

它給了我一個invalid_profile響應。

Slack 不會以兼容的響應來響應飛行前OPTIONS請求。

通過確保它符合作為所謂的“簡單請求”處理的要求,可以完全避免預檢。

值得注意的是,確保內容類型是application/x-www-form-urlencoded ,將請求正文序列化以匹配並且不要使用Authorization標頭來傳遞您的不記名令牌,而是將其作為參數傳遞到您的請求( token ) 中。

不知道為什么這如此困難,以下是對 Slack API 的有效POST請求:

// this.profile -> is the object with the status_* fields
const body = `profile=${JSON.stringify(this.profile)}&token=some_token`

this.$axios.post('https://slack.com/api/users.profile.set', body, {
  timeout: 10000,
  transformRequest(data, headers) {
    delete headers.common['Content-Type'];
    return data;
  }
}).then(res => {
  console.log(err)
}).catch(err => {
  console.log(err)
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM