怎样处理el-upload上传文件跨域问题

最近更新时间 2020-03-14 16:29:13

在使用 el-upload 组件上传文件时遇到跨域问题:

Vue CLI 项目在本地运行,服务器在另外一台机器上,会遇到跨域问题。

点击上传图片按钮,在 Console 中出现两条错误信息,如下所示:

注意:Access to XMLHttpRequest at 'http://file.example.com/api/upload' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
注意:VM8745:1 POST http://file.example.com/api/upload net::ERR_FAILED

已经添加了 Allow Origin 不过还是不能解决问题:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
Access-Control-Allow-Origin: *

解决方法:

需要处理  OPTIONS 方法,PHP 代码如下所示:

<?php

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') exit(0);
rss_feed