在此处发布之前,我确保在网上查找可能的问题解决方案。
我将 NuxtSSR
用于前端,并将 Laravel 7 作为后端 API,它现在具有本机 CORS 实现。我的前端应用程序在运行,http://localhost:3030
api 在http://gaminghub.test
.
这是我在cors.php
最新版本的 laravel 中所拥有的:
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => false,
'supports_credentials' => true,
];
使用邮递员,这是发送获取请求时返回的内容http://gaminghub.test/api/products?category=play-card
:
{
"data": [
{
"id": 1,
"name": "Xiaomi",
"price": 2000000,
"description": "Best value for money",
"slug": "xiaomi"
}
],
"links": {
"first": "http://gaminghub.test/api/products?page=1",
"last": "http://gaminghub.test/api/products?page=2",
"prev": null,
"next": "http://gaminghub.test/api/products?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 2,
"path": "http://gaminghub.test/api/products",
"per_page": 1,
"to": 1,
"total": 2
}
}
nuxt.config.js 包括:
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
baseURL: "http://gaminghub.test/api",
credentials: true
},
product.vue
包含以下内容以检索数据:
<script>
export default {
data() {
return {
product: null
}
},
async asyncData({params, app}) {
let res = await app.$axios.$get(`products/?category=${params.slug}`)
return {
product: res.data
}
},
}
</script>
所以,基本上,当我点击每个类别时,他们会发送一个 get 请求api/products?category=clicked-category-slug
,导致控制台出现以下错误:
Access to XMLHttpRequest at 'http://gaminghub.test/api/products/?category=play-card' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
网络请求标头包含以下内容:
Request Headers
Provisional headers are shown
Accept: application/json, text/plain, */*
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9nYW1pbmdodWIudGVzdFwvYXBpXC9hdXRoXC9sb2dpbiIsImlhdCI6MTU4MzU3MjQ4MiwiZXhwIjoxNTgzNTc2MDgyLCJuYmYiOjE1ODM1NzI0ODIsImp0aSI6ImdYY1Q3WGRSVnFXdUpocFIiLCJzdWIiOjMsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.t4JLsLLE6WIFZp67hbafZl8YTLlzN2WyQVw11mETMNQ
Referer: http://localhost:3000/categories/play-card
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36
当我重新加载浏览器时,错误消失并返回预期的数据。Nuxt 正在universal ssr
模式下运行。
我需要一些指导来了解可能导致此问题的原因。我肯定错过了什么