怎樣處理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