我正在尝试制作一个 API 以使用 Node.js 服务器上传文件。我收到 undefined
响应。
我正在学习本教程 https://www.youtube.com/watch?v=UtfZ-5WKpro
Node .js:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("*", function(req, res) {
res.end(JSON.stringify(req.files) + "\n");
});
console.log("Server at 8080");
app.listen(8080);
HTML
<html>
<head>
<form method="post"
enctype="multipart/form-data"
action="http://localhost:8080">
<input type="file" name="myimage" />
<input type="submit" name="submit" value="submit"/>
</form>
</head>
</html>
点击提交后,我得到了undefined
响应。
最佳答案
bodyParser.json()
…所以你已经为 JSON 格式的请求设置了一个解析器
enctype="multipart/form-data"
…但您没有发出 JSON 格式的请求。
参见 the documentation for body-parser :
This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
…后面是建议列表。
选择一个可以处理多部分请求的模块并使用它来代替您当前的选择。
关于javascript - 使用 HTML 将文件上传到 Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40483363/