I need to upload a file in React and then send it to an Express server (I'm new to Express so it's hard for me),
I succeed to upload the file in my React Component, but now I don't know how to send it to my back-end server made with Express.
What do I need to use ? Axios or Fetch ? Get or Post ? Thank you !
my App.js file (front-end)
uploadFile = () => {
const { currentFileName, currentFileType } = this.state;
if (currentFileName && currentFileType) {
fetch('http://localhost:5000/upload/files', {
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(this.state)
})
.then((res) => res.json())
.then(res => {
this.setState({
errorMessage: "",
successMessage: `Votre fichier ${currentFileName} a bien été uploadé !`
});
console.log(res);
console.log(res.data);
})
} else {
this.setState({
errorMessage: "Veuillez choisir un fichier avant d'appuyer sur le bouton Upload !"
});
}
}
and my server.js file (back-end)
const express = require('express');
const app = express();
const router = express.Router();
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/upload/files', (req, res) => {
var fileName = req.body.currentFileName;
var fileType = req.body.currentFileType;
console.log('Nom du fichier: ' + fileName + ' ' + 'Type du fichier: ' + fileType);
res.send(fileName + fileType);
});
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);
I expect to get the state datas in localhost:5000/upload/files but when I go on the URL I have the message "Cannot GET /upload/files"
Can someone help me please ? Thank you !