#laravel #axios #cors #nuxt.js
Вопрос:
Недавно я перенес свой проект Laravel Nuxt с локального на удаленный сервер. Ларавель работает на «http://laravelexample.com» домен и Nuxt запущены в другом домене «http://nuxtexample.com». У меня не было ошибок CORS во время работы на локальном хосте, все запросы/страницы работают так, как ожидалось, но при попытке в серверной среде работает только около половины запросов API, другие продолжают выбрасывать:
Доступ к XMLHttpRequest по адресу ‘http://laravelexample.com/api/XXXXX/» от источника «http://nuxtexample.com» заблокирован политикой CORS: Ответ на предполетный запрос не проходит проверку контроля доступа: Перенаправление не разрешено для предполетного запроса.
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) {
}
}
}
Пример вызова $axios, который вызывает ошибку CORS:
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, есть ли шанс, что кто-то столкнулся с чем-то подобным и сумел придумать какое-то исправление?
Любая помощь или идеи будут высоко оценены, так как это действительно стало крайне неприятным.
Комментарии:
1. Есть ли какой-либо пакет, который вы настроили для обработки CORS в
laravel
конце?
Ответ №1:
вы внедрили промежуточное программное обеспечение CORS для Laravel? если нет, то это может быть так.
попробуйте этот пакет, он устанавливает промежуточное программное обеспечение CORS для вашего проекта.