这里我的代码遇到了一个小问题。
我做什么
我在后端(在端口 8000 上)有一个 Laravel 应用程序,我在其中创建了一个 CORS 中间件,允许我从我的前端(在端口 8080 上)发出跨源请求
这是我的中间件 Cors
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', env("CORS_DOMAINS", 'http://localhost:8080'))
->header('Access-Control-Allow-Methods', 'OPTIONS,POST,GET ,PUT, PATCH, DELETE')
->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-type, Authorization', 'Accept-Language','Content-Disposition', 'Accept');
}
}
到目前为止,如果我使用 vue-resource 发出简单的请求,一切都运行良好。但是当我将 formData 作为数据传递时,CORS 失败。
我创建了一个用于上传文件的 Javascript 类
在接下来的几行中,只有这一行我们感兴趣(它是发出 XHR 请求的那一行):
return this.vm.$http.post(this.options.url, this.data)
我的上传类
class Upload {
defaultOptions = {
extensions: null,
maxSize: null,
multiple: false,
inputName: 'file'
}
errors = []
constructor (files, Vue, options) {
this.files = files
this.vm = Vue
this.options = Object.assign(this.defaultOptions, options)
this.data = new FormData()
return this.upload()
}
upload () {
if (!this.files.length) return
for (let i = 0; i < this.files.length; i++) {
if (this.checkFile(this.files[i])) {
this.pushToData(this.files[i])
} else {
this.errors.forEach((error) => this.options.errorsCallback(error))
}
}
for (let key in this.options.params) {
if (this.options.params.hasOwnProperty(key)) { this.data.append(key, this.options.params[key]) }
}
return this.vm.$http.post(this.options.url, this.data)
}
checkFile (file) {
return this.checkSize(file) && this.checkExtensions(file)
}
checkSize (file) {
if (this.options.maxSize && file.size > this.options.maxSize) {
this.errors.push('The file `' + file.name + '` size must not exceed' + this.options.maxSize)
return false
}
return true
}
checkExtensions (file) {
if (this.options.extensions && !this.options.extensions.includes(file.type.split('/')[1])) {
this.errors.push('The file `' + file.name + '` must have one of theses extensions :' + this.options.extensions.join(','))
return false
}
return true
}
pushToData (file) {
this.data.append(this.options.inputName, file)
}
}
export default Upload
我想要什么
我希望在发送 formData 时查询成功
我得到了什么
我收到一条消息,指出缺少 Access-Control-Allow-Origin header ,但我的 Cors 中允许使用此 header 。我不明白这个错误。
最佳答案
CORS 不是这里的真正问题,您的中间件工作正常。直接看上面,您会注意到一个较早的错误说 500 (Internal Server Error)
当您的服务器抛出 500 错误时,Chrome 偶尔会认为这是一个 CORS 问题。修复 500 错误,CORS 问题就会消失。
关于javascript - 上传文件时 CORS 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144463/