简体   繁体   English

XMLHTTPRequest为CORS设置适当的标题

[英]XMLHTTPRequest Setting Proper Headers for CORS

I am getting a CORS error when attempting to upload a file. 尝试上传文件时出现CORS错误。 The normal header responses I set up on other pages to get data don't seem to work, I believe I need to properly write the headers in the HTTPRequest but I am not sure how. 我在其他页面上设置的常规标题响应似乎无法正常工作,我相信我需要在HTTPRequest中正确编写标题,但不确定如何。 It should be after I open the request from what I can tell. 应该在我打开可以告诉我的请求之后。 Here is my my code: 这是我的代码:

UploadDocument.js UploadDocument.js

   var fd = new FormData();
   var pro = $("#pro").val(); 

   fileArray[index].submit = true; 

   fd.append("name" + index, "pdf2");
   fd.append("size" + index, fileArray[index].size);
   var fileDate = new Date(fileArray[index].lastModifiedDate);
   var currentDate = new Date();
   fd.append("fileDate" + index, fileDate.getTime());
   fd.append("uploadDate" + index, currentDate.getTime());
   fd.append("officialDate" + index, $('#date').val());
   fd.append("extension" + index, fileArray[index].name.split('.')[1]);
   fd.append("program_id" + index, pro);
   fd.append('file' + index, fileArray[index]);    

   fd.append("length", fileArray.length);
   var request = new XMLHttpRequest();
   request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            that.prop('disabled', true);
            that.text("Done!");
            that.parent().siblings().children(".deleteBtn").prop("disabled", true); 
        }
     };
   request.open("POST", locationOfServlet, true);
   request.send(fd);

Here is how I handle the headers in the servlet: 这是我处理Servlet中标头的方式:

RecieveFiles.java RecieveFiles.java

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS, DELETE");
        response.addHeader("Access-Control-Max-Age", "86400");

May be this help you https://developer.mozilla.org/enUS/docs/Web/API/FormData/Using_FormData_Objects 可能对您有帮助https://developer.mozilla.org/enUS/docs/Web/API/FormData/Using_FormData_Objects

Do you specified "multipart/form-data" attribute in the form? 您是否在表单中指定了“ multipart / form-data”属性?

<form enctype="multipart/form-data">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM