【发布时间】:2021-05-19 07:52:40
【问题描述】:
目标
我正在尝试从 Vue 3 打字稿前端向 Symfony 5 API 发送请求。使用NelmioCorsBundle 请求在 Insommia(邮递员)中有效,但在 Chrome、Safari 和 Firefox 中无效。
错误
CORS 策略已阻止从源“http://localhost:8080”获取“https://localhost:8000/api/users/6”的访问权限:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
前端请求(Vue):
import { onMounted, ref } from 'vue'
import { useStore } from 'vuex'
export default {
name: 'Home',
setup () {
const message = ref('Please login...')
const store = useStore()
onMounted(async () => {
try {
const response = await fetch('https://localhost:8000/api/users/6', {
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
})
console.log(response)
const user = await response.json()
message.value = `Hello ${user.name}`
await store.dispatch('setAuth', true)
} catch (e) {
console.log(e)
}
return {
message
}
})
}
}
Symfony 中的 NelmioCorsBundle 配置:
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/': null
在 .env 文件中,CORS_ALLOW_ORIGIN 是这样定义的:
CORS_ALLOW_ORIGIN='^http?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
我的尝试
- 我尝试在 NelmioCorsBundle 和 index.php 中设置 Access-Control-Allow-Origin 标头
- 我已尝试将 'http://localhost:8080' 作为 allow_origin。
- 我尝试在 index.php 文件中务实地设置不同的标头,结果却陷入了一个错误的兔子洞。
- 我还尝试了文档中关于 How to ignore preflight requests on New Relic? 的建议,此
FilterResponseEvent类不存在(因此重新安装了 NelmioCorsBundle,但没有效果。)
【问题讨论】: