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

Time:05-05

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().

Any help would be much appreciated.

CodePudding user response:

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

Console log

Network log

Thank you

CodePudding user response:

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));
  • Related