ng2-file-upload跨域上传不了

错误信息:

Failed to load http://localhost:9000/partner/upload: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8888' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

错误原因:浏览器不允许发送凭据和通配符源的组合。

解决办法1:

修改项目中的\node_modules\ng2-file-upload\file-upload\file-uploader.class.js源码,

注释掉第277行:

//xhr.withCredentials = item.withCredentials;

解决办法2:

this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };

例如:

......

import { FileUploader } from 'ng2-file-upload';

// const URL = '/api/';
const URL = 'http://localhost:9000/partner/upload';

@Component({
  selector: 'partner-form',
  templateUrl: './partner-form.component.html',
   styleUrls: ['./partner-form.css']    
    
})
export class PartnerFormComponent implements OnInit {
    
  public uploader:FileUploader = new FileUploader({url: URL});
  
  public hasBaseDropZoneOver:boolean = false;
  public hasAnotherDropZoneOver:boolean = false;
 
  public fileOverBase(e:any):void {
    this.hasBaseDropZoneOver = e;
  }
 
  public fileOverAnother(e:any):void {
    this.hasAnotherDropZoneOver = e;
  }

  constructor(private route: ActivatedRoute, private partnerService: PartnerService) {
    ......
  }
    
  /**
   *    初始化方法
   */
  ngOnInit() {
   
    this.uploader = new FileUploader({
    url: URL,   
    method: "POST",    
    itemAlias: "myuploader"
    });
    
    this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; };
    
  }

  ......
    
}

详情请参考ng2-file-upload官方的issue:

https://github.com/valor-software/ng2-file-upload/issues/1018

 

你可能感兴趣的:(Angular)