Home > Software engineering >  Node JavaScript Heroku - CORS Works Successfully With All API calls Exept When Uploading Image API
Node JavaScript Heroku - CORS Works Successfully With All API calls Exept When Uploading Image API

Time:07-08

Our web app has many apis that fetch from a node server deployed on heroku. All the apis work successfully except for one of the api which allow users to upload images to the node server. It worked fine in localhost but when we deployed it to production on heroku we are getting has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. We tried some of the suggestions on stackoverflow but none helped. CORS error only occurs with this particular api. All the other apis work just fine. Do cors have another approach or something when it comes to working with images?

***SERVER***
const express = require('express');
const bodyParser =  require('body-parser')
require('dotenv').config();
const https = require('https');
const port = process.env.PORT || 5000;
const app = express();
const cors = require('cors');

//Setting up the cors config
app.use(cors());


//Prevent application from crashing if incorrect route
app.all('*', (req, res, next) =>{
  const err = new Error(`Requested URL ${req.path} not found!`);
  err.statusCode = 404;
  next(err);
})

app.use((err, req, res, next) =>{
  const statusCode = err.statusCode || 500;
  res.status(statusCode).json({
    success: 0,
    message: err.message,
    stack: err.stack
  })
})


//Serve static files if in production
if(process.env.NODE_ENV === 'production'){

  //Set static folder
  app.use(express.static('client/build'));

  app.get('*', (req, res) =>{
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  });
}



app.listen(port, () => console.log(`Server started on port ${port}`));
***FRONTEND FETCH***
  let response = await fetch('"OUR HEROKU ROUTE"/uploadDesign',{
              method:'POST',
              body:JSON.stringify(data),
              headers:{
                'Content-Type':'application/json',
                'Accept':'application/json, text-plain */*'
              }
            })

CodePudding user response:

This issue is something developers face a lot and it could be for various reasons. Based on your question I think you installed and are using the cors package properly. So this has to do something with your server image api route. Is the folder in which you store your images empty when you deploy it? If so, try adding an image in it because if it’s empty then that folder will not be created in heroku server.

  • Related