使用 Vue.js 和 Axios 向 Mailchimp 提交表单导致 CORS 错误

Form submission to Mailchimp using Vue.js and Axios results in CORS error

我的 Vue.js 应用程序中有一个组件可以使用 Axios 从表单向 Mailchimp 提交电子邮件。

我在 Mailchimp 的 post URL 中读到要绕过 CORS,我需要使用 post-json 版本并将 &c=? 添加到URL。我还将我的请求方法从 POST 更新为 GET 并序列化了我的表单输入。

Component.vue

<mailchimp-subscribe action="https://example.us15.list-manage.com/subscribe/
post-json?u=xxx&amp;id=xxx&amp;c=?"></mailchimp-subscribe>

MailchimpSubscribe.vue

<template>
  <form @submit.prevent="subscribe">
    <input v-model="email" type="email" name="EMAIL" value="" placeholder="Email Address" required>
    <input class="button" type="submit" value="Subscribe">
  </form>
</template>

<script>
  import axios from 'axios'

  export default {
    name: 'MailchimpSubscribe',
    props: {
      action: {}
    },
    data: () => ({
      email: '',
      response: {}
    }),
    methods: {
      subscribe: function (event) {
        axios({
          method: 'get',
          url: this.action,
          data: JSON.stringify(this.email),
          cache: false,
          dataType: 'json',
          contentType: 'application/json; charset=utf-8'
        })
        .then(response => {
          console.log(response)
        })
        .catch(error => {
          console.log(error)
        })
      }
    }
  }
</script>

使用上面的代码,我仍然得到以下错误:

Failed to load https://example.us15.list-manage.com/subscribe/post-json?u=xxx&id=xxx&c=?: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

我是否遗漏了一个步骤?

您的服务器(后端)必须以完全相同的方式响应 header。

即:https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

例如 Axios get/post(没关系):

const configAxios = {
  headers: {
    'Content-Type': 'application/json',
  },
};
axios.post('api/categories', configAxios)
  .then((res) => {
    this.categories = res.data;
    console.log(res);
  })
  .catch((err) => {
    console.warn('error during http call', err);
  });

例如server-side。我喜欢Symfony4,它用的是NelmioCorsBundle,看看allow_origin: ['*']。这很简单,如果你使用 Symfony。

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: ['*']
        allow_headers: ['Content-Type']
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth', 'Content-Type', 'Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['X-Custom-Auth', 'Content-Type']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']

如果您不直接使用服务器,请与您的供应商核实这种细微差别。

这个header也可以通过例如Nginx来传输,这不是最好的主意。

例如,查看:

add_header Access-Control-Allow-Origin *;

server {
    listen 8080;
    server_name site.local;
    root /var/www/site/public;

    location / {
       add_header Access-Control-Allow-Origin *;

        # try to serve file directly, fallback to index.php
        try_files $uri /index.php$is_args$args; 
    }

    location ~ ^/index\.php(/|$) {
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.*)$;
        include fastcgi_params;
        # When you are using symlinks to link the document root to the
        # current version of your application, you should pass the real
        # application path instead of the path to the symlink to PHP
        # FPM.
        # Otherwise, PHP's OPcache may not properly detect changes to
        # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
        # for more information).
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_param DOCUMENT_ROOT $realpath_root;
        # Prevents URIs that include the front controller. This will 404:
        # http://domain.tld/index.php/some-path
        # Remove the internal directive to allow URIs like this
        internal;
    }

    # return 404 for all other php files not matching the front controller
    # this prevents access to other php files you don't want to be accessible.
    location ~ \.php$ {
        return 404;
    }

    error_log /var/log/nginx/project_error.log;
    access_log /var/log/nginx/project_access.log;
}

值得注意的是,如果没有数据传递,它会删除Content-Type。数据必须始终传输或 null。这很奇怪,而且具有误导性。