javascriptreactjsexpresshttp-status-code-413

Cross origin error when uploading a file to express server


So I use React to upload a file to my express server, doing this localy works however when I push the code to my nginx express server I keep on getting Cors errors. How would I be able to solve this problem, I currently user cors package ?

app.use(cors({
  "origin": "*",
  "methods": "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}))



var multer  = require('multer')

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, databasepath + 'pdf-folder/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})

var upload = multer({ storage: storage })

router.post('/uploadfolder',[authJWT.authenticateJWT,authJWT.isAdmin,upload.single('file')], adminController.uploadfolder);




exports.uploadfolder = function (req,res,next){
    
    let dates = JSON.parse(req.body.Dates)
    const newFolder = new Folder_PDF(
        {
            name: req.file.originalname,
            validFrom: dates.validFrom,
            validTill: dates.validTill
        }
    );
    
    newFolder.save((err,folder) => {

        if(err){
            return res.status(500).send({message: err});

        }

        return res.status(200)
    })
}

And my front end is just a simple dataform, however since this is a cors error I bet it is a server error:

 uploadFile = () =>{


        let data = new FormData();
        data.append( 'file', this.state.file, 'a file title' )
       

        const options = {
            onUploadProgress: (progressEvent) => {
                const {loaded, total} = progressEvent;
                let percent = Math.floor( (loaded * 100) / total )

                if( percent <= 100 ){
                    this.setState({ uploadPercentage: percent })
                }

                if(loaded === total){
                   // window.window.location.reload()
                }
            }
        }
        axios.post(apiLink+'admin/uploadfolder', data, options).then(res => {
        }).catch(err => console.log(err))
    }


Solution

  • The problem wasn't really cors, it was a 413 error. The file was to large, you have to set it in your nginx config file: client_max_body_size 2M;