Slack API Vue JS 中 axios 的 CORS 错误

Slack API CORS error with axios in Vue JS

我正在使用 Capacitor JS 和 Nuxt JS 构建一个应用程序来与 Slack API 交互,这样我就可以设置我的 Slack 状态,我创建了一个 Slack 应用程序并有一个 xoxp- 令牌在我通过 Postman 使用 POST 请求到达端点时工作正常,但是从我的浏览器(本地主机)和 phone 上的 运行 应用程序我得到了以下 CORS 错误:

Access to XMLHttpRequest at 'https://slack.com/api/users.profile.set' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

现在这看起来很愚蠢,因为您 必须 使用 authorization header 来提供用于身份验证的 Bearer 令牌,但即使在暂时省略它之后, CORS 错误仍然存​​在。

我正在尝试 POST 到达 users.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
  })
},

更新

我有一个函数可以将我的请求 body 转换为来自我的数据的查询字符串,如下所示:

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

要转换的查询字符串函数body

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 没有以兼容的响应响应 pre-flight OPTIONS 请求。

通过确保它符合作为 so-called "simple request".

处理的要求,完全避免预检检查

值得注意的是,确保 content-type 是 application/x-www-form-urlencoded,序列化请求 body 以匹配并且不要使用 Authorization header 传递您的承载令牌,而是将其作为 argument in your request (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)
})