Tomcat 端点 CORS 策略没有响应 "Access-Control-Allow-Origin" header

Tomcat endpoint CORS policy responding with no "Access-Control-Allow-Origin" header

我正在尝试使用 dropzone.js 向我的本地 Tomcat 服务器发送 post 请求,但是,chrome 正在响应说明。

Access to XMLHttpRequest at 'https://testserver.local/upload' from origin 'http://localhost:7887' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

和 dropzonejs 将鼠标悬停在上传上时的状态

Server responded with 0 code.

但是在我的端点中,我有以下允许上述来源的 doOptions。

我是不是在我的 CORS 选项中遗漏了什么或者这是一个 dropzonejs 问题?

    @WebServlet(value = "/upload", loadOnStartup = 0)
public class UploadEndpoint extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    protected void doOptions(HttpServletRequest req,
            HttpServletResponse resp)
            throws ServletException, IOException
    {
        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:7887");
        resp.setHeader("Access-Control-Allow-Methods", "POST GET HEAD");
        resp.setHeader("Access-Control-Allow-Headers", "*");
    }

        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form."); }
            ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
            PrintWriter writer = response.getWriter();
            try
            {
                List<FileItem> items = uploadHandler.parseRequest(new ServletRequestContext(request));
                for (FileItem item : items)
                {
                    if (!item.isFormField())
                    {
                        File file = new File(request.getServletContext().getRealPath("/") + "uploads/", item.getName());
                        item.write(file);
                    }
                }
            }
            catch (FileUploadException e)
            {
                throw new RuntimeException(e);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
            finally
            {
                writer.close();
            }
        }
    }

这是网页(为简单起见已删除绒毛),当然你需要相关的dropzonejs JavaScript文件和CSS文件。

<html>
    <head>
        <script src="dropzone.js"></script>
        <link rel="stylesheet" type="text/css" href="dropzone.css">
    </head>
    <body>
        <form action="https://trainor.org.uk:19001/Music/upload" class="dropzone" id="drop_zone"></form>
    </body>
</html>

如果您的 AJAX 请求包含自定义 headers.

,则 OPTIONS 请求用于 CORS 预检

您的请求未触发预检,因此它不会发送 OPTIONS 请求,也不会看到那些 headers。

您需要在 POST 响应中提供那些 headers。