1 year ago

#75200

test-img

yefee

How can i send file from react to node,js

I want send file from react to node.js and i want save file with multer. I tried this code but i getting this error on server:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

and i get this on client :

{}

my react code here:

function mainPage(props){

    function goFiles(){
        return props.wheregoing(2)
    }

    function sendFile(event){
        const formData = new FormData();
        console.log(formData)
        const file = event.target.files[0]
        formData.append('file', file)
        axios.post('http://localhost:5000/file', formData).then(r=>{
            console.log(r.data);
        })
    }

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const inputFile = useRef(null)
    return(
        <div className="mainpage">
            <input type='file' id='file' ref={inputFile} style={{display: 'none'}} name="images" onChange={(event) => sendFile(event)}/>
            <button onClick={() => inputFile.current.click()}>
                    <i className="fas fa-upload"></i>
                    Upload files
            </button>
</div>
    )
}

my express code here:

const express = require('express')
const app = express()
const cors = require('cors')
const multer = require('multer');

let upload = multer({dest:'files/'});

app.post('/file',upload.single('file'), (req, res, next) =>{
    res.send(req.body);
    try {
        res.send(req.file);
    }catch(err) {
        res.send('something are wrong, life sucks');
    }
})

node.js

reactjs

express

multer

0 Answers

Your Answer

Accepted video resources