首页 > 解决方案 > Vue JS 中 axios 的 Slack API CORS 错误

问题描述

我正在使用 Capacitor JS 和 Nuxt JS 构建一个应用程序来与 Slack API 交互,以便我可以设置我的 Slack 状态,我已经创建了一个 Slack 应用程序并且有一个令牌,当我通过请求xoxp-到达端点时它工作得很好POST通过邮递员,但从我的浏览器(本地主机)和手机上正在运行的应用程序中,我收到以下 CORS 错误:

从源“http://localhost:3000”访问“https://slack.com/api/users.profile.set”的 XMLHttpRequest 已被 CORS 策略阻止:访问控制不允许请求标头字段授权- 预检响应中的允许标头。

现在这似乎很愚蠢,因为您必须使用authorization标头来提供 Bearer 令牌进行身份验证,但即使暂时省略了这一点,CORS 错误仍然存​​在。

我正在尝试到users.profile.setPOST的端点查看另一种方法

我的 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回应。

标签: javascriptnode.jsvue.jsslack-api

解决方案


Slack 不会OPTIONS使用兼容的响应来响应飞行前请求。

通过确保它与作为所谓的“简单请求”处理的要求相匹配来完全避免预检检查。

值得注意的是,确保内容类型为application/x-www-form-urlencoded,序列化请求正文以匹配并且不要使用Authorization标头来传递您的不记名令牌,而是将其作为参数传递给您的请求( token)。


推荐阅读