I have a react application (using webpack and running on localhost) and I am trying to send a text file to a server that I created separately, still locally using Node.js (also on localhost but different port). For file upload, I use a library called Dropzone. To send the file over, I am using a library called superagent.
The problem here is that when I send over a file, the server receives the request but not the file. Right before I send the file, I console logged the file to make sure that the object is available:
I've been trying the solutions that I found online but to no avail. I even console logged the request on the server side but found no req.body/req.files. I figured that I am doing something wrong with the superagent library. Below are the codes that I've tried. Any help would be greatly appreciated.
SERVER SIDE CODES
app.js(1st test)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Metadata = require('./Metadata.model');
var cors = require('cors');
const fs = require('fs');
var port = 3000;
var myDir = ('./tmp');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors({origin: 'http://localhost:8080'}));
app.post('/upload', function(req, res) {
try {
fs.accessSync(myDir);
} catch (e) {
fs.mkdirSync(myDir);
};
console.log(req);
});
app.js(2nd test)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Metadata = require('./Metadata.model');
var cors = require('cors');
const fs = require('fs');
var fileupload = require('fileupload').createFileUpload('/tmp').middleware;
var port = 3000;
var myDir = ('./tmp');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors({origin: 'http://localhost:8080'}));
app.post('/upload', fileupload, function(req, res) {
console.log(req);
});
CLIENT SIDE CODES
test_page.js(1st test)(full code)
import React, { Component } from 'react';
import Dropzone from 'react-dropzone';
var request = require('superagent');
const ROOT_URL = 'http://localhost:3000';
class TestPage extends Component {
onDrop(files){
files.forEach((file) => {
console.log(file);
request.post(`${ROOT_URL}/upload`)
.attach(file.name, file)
.end((err, res) => {
console.log(err);
console.log(res);
})
});
};
onOpenClick(){
this.refs.dropzone.open();
}
render(){
return(
<div>
<Dropzone ref="dropzone" onDrop={this.onDrop}>
<div>Drop files here</div>
</Dropzone>
<button type="button" onClick={this.onOpenClick.bind(this)}>
Open Dropzone
</button>
</div>
);
}
}
export default TestPage;
test_page.js(1st test)(changed code)
onDrop(files){
files.forEach((file) => {
console.log(file);
request.post(`${ROOT_URL}/upload`)
.set("Content-Type", "text/plain")//also tried ("Accept", "text/plain")
.send(file)
.end((err, res) => {
console.log(err);
console.log(res);
})
});
};