我对Node.js都是陌生的,并且会做出反应。 我正在将选定的文件从react(前端)发送到节点(后端),在那里我可以上传文件并将文件转换为json对象。但是当我尝试从request.body访问选定的文件时,它说selectedFile是未定义的。
节点代码:
const express = require("express");
const bodyParser = require("body-parser");
const excelToJson = require("convert-excel-to-json");
const upload = require("express-fileupload");
const cors = require("cors");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(upload());
let corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
app.use(cors(corsOptions));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.post("/upload", function(request, response, next) {
if (request.body.selectedFile) {
let file = request.body.selectedFile;
let dest = __dirname + "/uploads/sample.xlsx";
file.mv(dest, function(err) {
if (err) {
response.send("File not found");
} else {
const result = excelToJson({
sourceFile: "sample.xlsx"
});
response.json(result);
}
});
} else {
response.send("File not Found");
}
});
app.listen(4001, function() {
console.log("App is listening at port 4001");
});
反应代码:
import React from "react";
import axios from "axios";
import logo from "./logo.svg";
import "./App.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: ""
};
this.handleFileUpload = this.handleFileUpload.bind(this);
this.handleUpload = this.handleUpload.bind(this);
}
handleFileUpload = function(event) {
this.setState({
selectedFile: event.target.files[0]
});
console.log(this.state.selectedFile);
};
handleUpload = function(event) {
event.preventDefault();
console.log(this.state.selectedFile);
let data = {
selectedFile: this.state.selectedFile
};
axios
.post("http://localhost:4001/upload", data)
.then(res => console.log(res))
.catch(err => console.log(err));
};
render() {
return (
<div>
<input
type="file"
name="fileSelected"
id="fileSelected"
onChange={this.handleFileUpload}
/>
<button type="submit" onClick={this.handleUpload}>
upload
</button>
</div>
);
}
}
export default App;