使用 axios 和 Slack API 时出现 CORS 问题

问题描述 投票:0回答:2

我正在使用浏览器中的 axios 与 Slack webhook API 进行交互。发送帖子时,我尝试使用

axios.post(url, data)

浏览器/axios向后端发送OPTION请求。选项请求中包含

access-control-request-headers:content-type

然而,Slack 的回应却是

access-control-allow-origin:*

但没有 access-control-allow-headers 标头。这会导致浏览器/XMLHttpRequest 抱怨

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

似乎一种解决方案是告诉 axios 在这种情况下不要发送内容类型标头,但我不知道该怎么做。

谢谢。

slack-api axios
2个回答
13
投票

基本上,您需要删除内容类型标头,这只能使用 hacky 方式来实现:

const url = 'https://hooks.slack.com/services/{YOUR_WEBHOOK}'
const data = {
  "text": "yo some text",
}
axios.post(url, JSON.stringify(data), {
  withCredentials: false,
  transformRequest: [(data, headers) => {
    delete headers.post["Content-Type"]
    return data
  }]
})

0
投票

如果有谁不必坚持使用axios

const feedback = { text: JSON.stringify(data) }; // this part is important
const url = "https://hooks.slack.com/services/{YOUR_URL}";
const feedbackInJSON = JSON.stringify(feedback);
fetch(url, {
 mode: "cors",
 credentials: "omit",
 cache: "no-store",
 redirect: "follow",
 method: "POST",
 body: feedbackInJSON,
 headers: {
   "Content-Type": "application/x-www-form-urlencoded",
 },
});
© www.soinside.com 2019 - 2024. All rights reserved.