【问题标题】:Laravel+Nuxt CORS getting blocked in production environmentLaravel+Nuxt CORS 在生产环境中被阻塞
【发布时间】:2021-06-13 21:46:09
【问题描述】:

最近我将我的 Laravel+Nuxt 项目从本地服务器移到了远程服务器。 Laravel 在“http://laravelexample.com”域上运行,而 Nuxt 在另一个域“http://nuxtexample.com”上运行。我在本地主机上运行时没有出现 CORS 错误,所有请求/页面都按预期工作,但是在服务器环境中尝试时,只有大约一半的 API 请求工作,其他人继续抛出:

CORS 策略已阻止从源“http://nuxtexample.com”访问“http://laravelexample.com/api/XXXXX/”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。

Laravel .htaccess:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>
<IfModule mod_rewrite.c>
php_value  upload_max_filesize  10M

    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On
   
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Nuxt .htaccess:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

nuxt.config.js:

import colors from 'vuetify/es5/util/colors'
export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  mode: 'universal',
  head: {
    titleTemplate: '[EB] - %s',
    title: 'X',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      {
        rel: "stylesheet",
        href:
          "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
      }
    ],
    script: [
      {
        src: "https://code.jquery.com/jquery-3.3.1.slim.min.js",
        type: "text/javascript"
      },
      {
        src:
          "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js",
        type: "text/javascript"
      },
      {
        src:
          "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js",
        type: "text/javascript"
      }
    ],
  },

  loading: { color: '#fff' },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],

  router: {
    middleware: ["clearValidationErrors"]
  },

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
    './plugins/mixins/user.js',
    './plugins/axios.js',
    './plugins/mixins/validation.js',
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/vuetify
    '@nuxtjs/vuetify',
  ],

  moment: {
    defaultTimezone: 'America/Chicago'
  },

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    '@nuxtjs/proxy',
  ],

  axios: {
   // Do away with the baseUrl when using proxy
    baseUrl: 'http://laravelexample.com/api/',
  },



  auth: {
        redirect: {
        login: "/login",
        logout: false
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: 'auth/login',
            method: 'post',
            propertyName: "meta.token"
          },
          user: {
            url: '/auth/user-profile',
            method: 'get',
            propertyName: 'data'
          },
          logout: {
            url: 'auth/logout',
            method: 'post'
          }
        }
      }
    }
  },

  // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify
  vuetify: {
    customVariables: ['~/assets/variables.scss'],
    theme: {
      dark: true,
      themes: {
        dark: {
          primary: colors.teal.lighten1,
          accent: colors.grey.darken3,
          secondary: colors.amber.darken3,
          info: colors.teal.lighten1,
          warning: colors.amber.base,
          error: colors.deepOrange.accent4,
          success: colors.green.accent3
        }
      }
    }
  },

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    extend (config, ctx) {
    }
  }
}

导致 CORS 错误的 $axios 调用示例:

getVendors()
{
  this.$axios.get(`/vendors`).then(res => {
    this.vendors = res.data.data;
  })

$axios 调用示例,可​​在服务器上运行且不会导致 CORS 错误:

    getBreakdowns() {
      let user_company = this.$store.getters['company/getCompany']
      this.$axios.get(`/breakdowns/${user_company}`).then(res => {
        this.breakdowns = res.data.data;
      })
    },
},

Google Chrome 网络选项卡在访问出现 CORS 错误的路径时显示此内容:

我已经尝试了各种不同的代理设置(但它仍然只适用于本地主机,但不适用于服务器)。如果这改变了某些东西,服务器正在使用 OpenLiteSpeed。但是似乎没有任何效果,而且我一直看到相同的 CORS 错误,是否有人遇到过类似的情况并设法想出某种修复方法?

任何帮助或想法都将不胜感激,因为这真的变得非常令人沮丧。

【问题讨论】:

  • laravel 端,您是否配置了任何用于处理 CORS 的包?

标签: laravel axios cors nuxt.js


【解决方案1】:

你是否为 Laravel 实现了 CORS 中间件? 如果不是,可能就是这种情况。

试试这个package,它会为您的项目设置一个 CORS 中间件。

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 2021-05-03
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 2017-09-14
    • 2020-09-18
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多