简体   繁体   English

POST请求中的空FormData

[英]Empty FormData in POST Request

I'm making a simple application that will upload a file a server that has been dragged and dropped onto a canvas. 我正在制作一个简单的应用程序,它将文件上传到已拖放到画布上的服务器上。

Here's a small sample of what the drag and drop code looks like: 这是拖放代码的一小部分示例:

var files = event.dataTransfer.files;
var formData = new FormData();
formData.append('files', files);

Using the debug tools, I know that files is correctly defined. 使用调试工具,我知道files定义正确。

Then, I make the request: 然后,我发出请求:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.send(formData);

But my server, running Node JS, gets an empty response body: 但是我的运行Node JS的服务器收到一个空的响应主体:

var express = require('express');
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: false
}));
app.post('/upload', function(req, res) {
    console.log(req.body.files);
    res.end();
});

I tried debugging on both the client and server side, but I can't figure it out. 我尝试在客户端和服务器端进行调试,但无法弄清楚。 Although, it seems weird to me that the formData object looks like: 虽然,对我来说, formData对象看起来像是很奇怪:

FormData {append: function}
    __proto__: FormData

Why isn't the appended files object showing up? 为什么未显示附加files对象?

Any insight as to what the problem is would be greatly appreciated! 任何有关问题是什么的见解将不胜感激!

Try changing 尝试改变

var files = event.dataTransfer.files;

to

var files = event.dataTransfer.files[0];

See https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects ; 参见https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects ; see also node-form-data 另见node-form-data

After too long of a time working on this problem, I finally figured it out. 经过很长时间的研究,我终于弄清楚了。 The issue was server-side; 问题出在服务器端。 my Express application was ignoring the body of the post since I have not explicitly set the bodyParser to accept JSON. 我的Express应用程序忽略了帖子的正文,因为我没有明确地bodyParser设置为接受JSON。

The Express setup for a POST method should be: POST方法的Express设置应为:

var express = require('express');
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // Configures bodyParser to accept JSON
app.use(bodyParser.urlencoded({
    extended: false
}));

With a sample routing method like: 使用以下示例路由方法:

app.post('/upload', function(req, res) {
    console.log(req.body.files);
    res.end();
});

It also is helpful to know that this server side setup can be tested by running something like this: 知道可以通过运行以下命令来测试此服务器端设置,这也很有帮助:

curl -d '{"file":{"name":"sample"}}' -H "Content-Type: application/json" http://localhost:8080/upload

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

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