我必须从浏览器(react-js)发送一个.rar文件。然后,我必须在服务器端接收该文件(express-js),以便可以对其执行进一步的操作。有人可以帮我吗?
我尝试使用multer(但我想多数民众赞成在上传文件时使用)。我尝试使用json和urlencoded的bodyParser中间件,但它们没有进一步处理我的请求,也没有将其传递给控制器。
客户端
sendData = () => {
const data = new FormData();
const { fileSelected, fileSelectedName } = this.state;
data.append('file', fileSelected);
if (fileSelectedName === 'THERM0001.rar') {
fetch('http://localhost:3001/thermometer/postReadings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({
// data: fileSelected,
// name: fileSelectedName
// })
body: data
})
.then(res => res.json())
.then(resp => alert(resp.message));
}
else {
alert(`There is no need for manual entry for ${fileSelectedName}.json`);
}
}
服务器端:
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import cors from 'cors';
import router from './routes';
const app = express();
const port = 3001;
const mongoDB = 'mongodb://127.0.0.1/thermometer';
mongoose.connect(mongoDB, { useNewUrlParser: true });
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json({limit: '50mb', extended: true}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cors());
app.use('/thermometer/', router);
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
SyntaxError:意外令牌-JSON中位置0 在JSON.parse() 在createStrictSyntaxError(/Users/aditmodi/Desktop/thermometer-server/node_modules/body-parser/lib/types/json.js:158:10) 在解析时(/Users/aditmodi/Desktop/thermometer-server/node_modules/body-parser/lib/types/json.js:83:15) 在/Users/aditmodi/Desktop/thermometer-server/node_modules/body-parser/lib/read.js:121:18 在invokeCallback(/Users/aditmodi/Desktop/thermometer-server/node_modules/raw-body/index.js:224:16) 完成时(/Users/aditmodi/Desktop/thermometer-server/node_modules/raw-body/index.js:213:7) 在IncomingMessage.onEnd(/Users/aditmodi/Desktop/thermometer-server/node_modules/raw-body/index.js:273:7) 在IncomingMessage.emit(events.js:197:13) 在endReadableNT(_stream_visible.js:1129:12) 在processTicksAndRejections(internal / process / next_tick.js:76:17)