502 and CORS Error File Upload with Multer?

Hi guys,

I keep getting the below when trying to upload a photo. Before this error I had an error saying that the file size was too large so I added a line in my nginx config to increase the filze size and that worked but now my getting the errors below. If I remove the 2 lines related to req.file like const path and photo:path then I can successfulyy create a post but without a photo. I fi add the 2 lines back then and submit then I get the 502 and CORS error.

EDIT
I forgot to mention that the file does upload as I can see that it’s added to my /public/images in my server folder but I still get the errors mentioned above but I can’t create a proper post with a photo

EDIT

Adding my nginx file since it may be an nginx problem?

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/*PROJECT NAME*/client/build/index.html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name *DO IP ADDRESS*;

        location ^~ /assets/ {
                gzip_static on;
                expires 12h;
                add_header Cache-Control public;
  }

        location / {
                proxy_http_version 1.1;
                proxy_cache_bypass $http_upgrade;

                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_pass http://localhost:5000;
                client_max_body_size 50M;
        }
location = /favicon.ico {
  log_not_found off;
}
}

Errors

has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

POST: net::ERR_FAILED 502 (Bad Gateway)

API

/* CORS */

const corsOptions = {
    origin: `${process.env.FRONTEND}`,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true,
    preflightContinue: false,
    optionsSuccessStatus: 204
}

router.use(cors(corsOptions))

// Create Posts
router.post('/post/newPost', upload.single('photo'), [
    check("title", "A title is required and must be at least 5 characters long")
        .not()
        .bail()
        .isEmpty()
        .bail()
        .isLength({ min: 5 })
        .bail()
        .trim(),
    check("category", "A category is required")
        .not()
        .bail()
        .isEmpty()
        .bail(),
    check("post", "A post is required and must be at least 5 characters long")
        .not()
        .bail()
        .isEmpty()
        .bail()
        .isLength({ min: 5 })
        .bail()
        .trim(),
], (req, res, next) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() })
    } else {

// If I remove the const path line along with the photo line below in the post object I can create a post but without a photo

        const path = "/public/images/" + (req.file ? req.file.filename : '');
        const post = {
            user: req.body.user,
            title: req.body.title,
            category: req.body.category,
            post: req.body.post,

// remove this line too and it works 
            photo: path
        };


        PostService.create(post)
            .then((post) => {
                res.status(200);
                res.set({ 'Content-Type': 'multipart/form-data' });
                res.json(post);
            }).catch((err) => {
                res.status(404);
                res.end();
            });



    }

});

CreatePost

const submitNewPost = (data) => {
        console.log(data);
        const formData = new FormData()
        formData.append('user', data.user);
        formData.append('title', data.title);
        formData.append('category', data.category);
        formData.append('post', data.post);
        formData.append('photo', data.photo[0]);

        (async () => {
            try {
                await axios.post(`${process.env.REACT_APP_URL}/api/blog/post/newPost`, formData)
                toast.success("View your profile for your new post!")
                reset()
            } catch (error) {
                if (error.response) setErrorsServer(error.response.data.errors);
                toast.error("Unable to create new post")
            }
        })();
        if (errorsServer) setErrorsServer('')

What happens if you just do app.use(cors()) at the top of the file that starts the server?

Hi, unfortunately I still get the same errors. I forgot to mention that the file does upload as I can see that one is added to my /public/images in my server folder but I still get the errors mentioned above. I will update the original post with this info

Hello ! Any update ?
Struggling with same issue

HI! Unfortunately I’m still struggling. I’ve been on this issue for awhile now and I’m not sure what’s wrong.

I was able to get rid of the CORS Error. What I did was edit my Nginx config to the below but I still get the POST 502 Bad Gateway Error.

add_header 'Access-Control-Allow-Origin' 'http://localhost:3000' always;
 add_header 'Access-Control-Allow-Headers' 'Content-Type' always;
 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';

Just fix my issue. PM2 was watching and nodemon was restarting server every time I was upload a picture in public folder.

2 Likes

That’s awesome congrats! Also, thanks for sharing. It may not apply to my situation but if anyone else lands on this question your reply might solve their situation.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.