Stuck with CORS API



我坚持使用API请求。我把请求从Vite服务器发送到Laravel服务器,但我得到了这个错误

访问XMLHttpRequest'http://127.0.0.1:8000/api/checkPrivate/?username=greta&电子邮件=&acceptNewLetter=false'来自原点'http://localhost:3000'已被CORS策略阻止:请求的上不存在"Access Control Allow Origin"标头资源

正如你所看到的,我在使用Laravel时同时使用了两台服务器http://127.0.0.1:8000而对于Vite服务器来说,只是一个不同的端口:3000。

我试图通过在Laravel 中创建中间件来禁用CORS

return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

我的前端请求

axios.get('http://127.0.0.1:8000/api/checkPrivate/', { 
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
params: {
username: this.username,
email: this.email,
acceptNewLetter: this.acceptNewLetter,
},
})
.then(response => {
if(response.data) {
console.log(response.data)
}
})

但这无济于事。你对我如何解决这个问题有什么意见吗?

我找到了解决方案,问题不在后端,而是在Vite服务器上。Vite服务器被阻止以从其他服务器获得响应,但我通过添加origin更改了Vite配置,它起了作用vite.config.js

export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
},
},
server: {
open: true,
origin: 'http://127.0.0.1:8080/'
},


})

最新更新