javascript - 上传文件时 CORS 失败

标签 javascript php vue.js

这里我的代码遇到了一个小问题。

我做什么

我在后端(在端口 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 。我不明白这个错误。 Une Image de L'erreur

最佳答案

CORS 不是这里的真正问题,您的中间件工作正常。直接看上面,您会注意到一个较早的错误说 500 (Internal Server Error)

当您的服务器抛出 500 错误时,Chrome 偶尔会认为这是一个 CORS 问题。修复 500 错误,CORS 问题就会消失。

关于javascript - 上传文件时 CORS 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50144463/

相关文章:

javascript - 检测页面中的所有iframe是否都有src

php - 防止重复数据进入mysql数据库

templates - Vue.js 本地模板变量

javascript - 数据作为对象和数组传递?

javascript - 简单的 Vuejs 验证代码无法按预期工作?

php - html解析错误无法在子元素关闭之前修改父容器元素

javascript - react native 导航: Conditionally render tab bar badge not working?

javascript - AngularJS 是否仅适用于单页应用程序 (SPA)?

php - 在 PHP 中获取第一维数组

php - 为什么 HTML 电子邮件的一部分在电子邮件客户端中显示为文本?