I am new to both nodejs and react. I am working on sending a selected file from react(front end) to the node (back end) where I can upload the file and convert the file into json object. but when I try to access the selected file from request.body, it says the selectedFile is undefined.
Node code:
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");
});
React code:
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;
multermodule in nodejs and you useFormDatain ReactJSFormDataworked for me