我的项目具有以下(简化的)结构:
-app
-uploads
-client
- dropzone.js
-server.js
我正在尝试使用 dropzone js
、Express JS
和 React JS
上传文件。但是,每次我将文件放入拖放区框中时,我都会在 console.log
中得到:
POST http://localhost:3000/uploads/ 404 (Not Found)
Not found
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /uploads/</pre>
</body>
</html>
./uploads
文件夹的位置是正确的,我很困惑为什么我不能从我的 React 组件向 Express 发出 POST
请求。任何帮助,将不胜感激!
React
组件有这个:
class Dropbox extends Component {
constructor() {
super();
this.state = {
selectedFile: [],
description: ''
}
}
onDrop = () => {
const { selectedFile, description } = this.state;
let formData = new FormData();
let xhr = new XMLHttpRequest();
formData.append('description', description);
formData.append('selectedFile', selectedFile);
xhr.open('POST', './uploads/', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.responseText);
} else {
console.log(xhr.statusText);
}
}
xhr.send(formData);
}
render() {
const selectedFile = this.state;
return (
<div>
<Dropzone onDrop={this.onDrop.bind(this)}>
<p>Drop PDF here</p>
</Dropzone>
<p>{this.state.selectedFile.map(f => <li>{f.name}</li>)}</p>
</div>
);
}
}
我的 server.js
文件是:
const port = process.env.PORT || 5000;
const express = require('express');
const multer = require('multer');
const uuidv4 = require('uuid-v4');
const app = express();
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './uploads/');
},
filename: (req, file, cb) => {
const newFilename = `${uuidv4()}${path.extname(file.originalname)}`;
cb(null, newFilename);
}
});
const upload = multer({ storage });
app.post('/', upload.single('selectedFile'), (req, res) => {
res.send();
})
app.listen(port, () => console.log(`Server listening on port ${port}`))
最佳答案
您还没有设置处理/uploads 的路由。您的 POST 操作将首先在/uploads 访问您的服务器,并且不关心它正在运行的系统的文件结构。您的服务器需要一个路由来知道如何处理它。
我想你的意图是使用你的 /
路由上传,所以你有几个选择:
- 将您的路线更新为
app.post('/uploads'...)
- 更新您的 POST 以点击
/
而不是/uploads
任何一个都应该解决这个问题。
关于javascript - 将文件上传到 Express JS 时找不到 ./uploads 文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630117/