在Axios POST请求(VueJS)上阻止了跨域请求

时间:2020-04-10 23:25:28

标签: forms api vue.js post vuejs2

我正在尝试在表单提交后发送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 ... enter image description here

我不知道是什么问题。我尝试了一堆东西。我将不胜感激任何帮助或建议。在此先感谢一吨。

注意:此问题在localhost和生产版本(Netlify)上均发生。

2 个答案:

答案 0 :(得分:1)

出于安全原因,我原来使用的电子邮件营销服务不允许进行客户端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',
    }
})

希望这会有所帮助。

答案 1 :(得分:1)

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

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