Ben Liger Ben Liger -4 years ago 99
React JSX Question

Basic file uploads with Node & React

I've built a React App to teach myself

. I'm using the boilerplate provided by Facebook called create-react-app which uses
to bundle the App. I'm at the point now where i'm trying to create an upload file function within the app. I stumbled upon something called Multer which when used with Express enables for fairly straight forward file uploads. I plan to use this and express for the file upload part of my app. Here is the code below with what i'm trying to achieve:


import React from 'react';
import testupload from './testupload/testupload';
var App = React.createClass({
testUpload(e) {
render() {
return (<div className="outer-most-container">
<form encType='multipart/form-data'>
<input type="file" method="post"/>
<button type="submit" onClick={this.testUpload}>submit</button>
}) export default App;


var express = require('express')
var multer = require('multer')
var upload = multer({
dest: 'uploads/'
var app = express()
var testupload = function() {'/profile', upload.single('avatar'), function(req, res, next) {})'/photos/upload', upload.array('photos', 12), function(req, res, next) {})
var cpUpload = upload.fields([{
name: 'avatar',
maxCount: 1
}, {
name: 'gallery',
maxCount: 8
}])'/cool-profile', cpUpload, function(req, res, next) {})
export default testupload;

I'm used to working with PHP when it comes to file uploads so my logic here is when you click the button to submit there is a prevent of the default event, then it executes the
function which was imported from another script. The error i'm getting at the moment is

Cannot read property 'prototype' of undefined

which is in the
so says the browser console. Not sure if my approach is the correct logic here so a push in the right direction would really help. What i'm finding particularly tough is determining where exactly the crossover from the front end JS to the server side JS is and if i'm attempting to execute the server side JS in the right place. I haven't found any good tutorials online on how to do this hence why i'm posting on here. Please let me know if anything is unclear as i'm fairly new to React &
so I appreciate some of the code above might not be very logical in some parts.

Answer Source

it looks like you're trying to import your Node code right in your React component. What you'll want to do is move your server code into another project, and run a server. you would add an app.listen(port, ....) to your server code, where port is your choice (create-react-app runs on 3000 by default, so pick something else). then, have your file upload code in your React application POST the files to your specified endpoints

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download