'Can't make Axios post request to Express server (CORS)

I've been trying to make a simple image upload form using react, axios and multer, but I can't figure out a way to deal with cors !

Here is my form (running on port 80 with create-react-app) :

<form onSubmit={uploadAvatar} enctype="multipart/form-data">
  <div className="form-group">
    <input type="file" className="form-control-file" id="avatar" onChange={e => setAvatar({ profileImg: e.target.files[0] })}/>
    <input type="submit" value="Uploader" className="btn btn-default"/>            
  </div>
</form>

And the corresponding handle function with Axis :

const uploadAvatar = e => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("avatar", avatar);
    axios.post("http://localhost:3000/pupilpic", formData, {
        headers: {
            "Content-type": "multipart/form-data",
            "Access-Control-Allow-Origin": "*"
        }
    }).then(res => console.log(res)).catch(err => console.log(err))     
}

I'm running a very basic Express server with multer (port 3000) :

    const express = require('express')
const cors = require('cors');
const multer  = require('multer');
const upload = multer({ dest: "../public/avatars/pupils/"});
const port = process.env.PORT || 3000;

const app = express();

app.use(cors());

app.get("/", (req, res) => {
res.send("Hellow !");
});

app.post('/pupilpic', upload.single('avatar'), function (req, res, next) {
  
  console.log(req.file);
})

app.listen(port, () => {
    console.log("Listening on port "+ port)
})

The issue is when I submit my form, request gets blocked by the browser even though I configured cors().

To be a bit more specific I added the browser errors down below. Please see the attached images.

Console log:

Console log

Network log:

Network log



Solution 1:[1]

Your middleware for POST /pupilpic lacks a res.end() statement or similar. Without that, the request never comes back, and that explains the "Code d'état: (null)" error in the console: it's just a timeout interpreted as a CORS error.

app.post('/pupilpic', upload.single('avatar'), function (req, res, next) {
  console.log(req.file);
  res.end();:
})

Solution 2:[2]

I think your issue come from your cors configuration. You should try to add a configuration as I do in the code below.

const corsOptions = {
  origin: "http://localhost:3000", //front end dns
  optionSuccessStatus: 200,
};
app.use(cors(corsOptions));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Heiko Theißen
Solution 2 DylanAumond