【问题标题】:Cross-Origin Request Blocked on Axios POST request (VueJS)在 Axios POST 请求(VueJS)上阻止跨域请求
【发布时间】:2020-04-10 23:25:28
【问题描述】:

我正在尝试在表单提交时发送 POST 请求并不断遇到 CORS 问题。我收到以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/lists/contacts.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/api/lists/contacts.
(Reason: CORS request did not succeed).

这是我的代码:

<template>
   <form @submit.prevent="subscribeEmail" method="post" enctype="multipart/form-data" action="">
     <input type="email" v-model="email" name="user_email">
     <button type="submit" name="button">Subscribe</button>
   </form>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    subscribeEmail() {
        axios({
            method: 'POST',
            url: `https://example.com/api/lists/${id}/contacts`,
            data: {
                "api_key": apiKey,
                "email_address":  this.email,
            },
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Content-type': 'application/json',
            }
        })
        .then(function (response) {
          console.log(response)
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
}
</script>

此外,这是我的请求的网络描述。由于某种原因,该方法是 OPTION...

我不知道问题出在哪里。我尝试了一堆东西。我真的很感激任何帮助或建议。非常感谢。

注意:本地主机和生产版本 (Netlify) 都会出现此问题。

【问题讨论】:

  • 必须在托管 API 的服务器上设置 CORS 标头,而不是由您发送它。否则,任何客户端都可以发送一个标头,强制降级远程服务器上的 CORS 策略。
  • OPTIONS 请求是 CORS 预检,请参阅 cors-errors.info/faq#a313。您需要在服务器上启用 CORS。在客户端中添加Access-Control-Allow-Origin 将无济于事。
  • 特里,裙子,当您提到服务器时,您是指我托管代码的服务器 (Netlify) 还是我将请求发送到的服务器 (example.com)?如果是后者,那么我不确定该怎么做,因为它是第三方服务。我想必须与他们联系。

标签: forms api vue.js post vuejs2


【解决方案1】:

尝试在没有 CORS 的情况下启动浏览器:

Linux 终端(Chrome 浏览器):google-chrome --user-data-dir="/var/tmp/Chrome" --disable-web-security

【讨论】:

  • 谢谢,这是唯一对我有用的东西......
【解决方案2】:

事实证明,出于安全原因,我使用的电子邮件营销服务特别不允许客户端 API 调用。

如果您遇到类似问题,请尝试联系提供 API 的服务。他们或许能提供帮助。

要绕过这一点,您可以使用的一种方法是通过代理引导请求。最流行的解决方案是使用https://cors-anywhere.herokuapp.com/。您基本上将此网址附加到您的请求中,如下所示:

axios({
    method: 'POST',
    url: `https://cors-anywhere.herokuapp.com/https://example.com/api/action`,
    data: {
       "api_key": apiKey,
       "email_address":  this.email,
    },
    headers: {
       'Access-Control-Allow-Origin': '*',
       'Content-type': 'application/json',
    }
})

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-03-28
    • 2022-01-05
    • 2017-02-06
    • 2021-11-15
    • 2018-06-28
    • 2022-01-28
    • 2019-10-11
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多