1

So I know this question has been asked many times, but I've searched for hours through so many similar stackoverflow questions and tried many solutions and non have worked so far. In fact I find it weird that the CORS error I'm getting below doesn't happen all the time. (I'll clarify below)

Access to XMLHttpRequest at 'http://127.0.0.1:4000/company/details/?ticker=AMD' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Firstly I am using React for frontend and express for backend

Part of the express code is shown below:

const rateLimit = require('express-rate-limit')
const helmet = require('helmet')
const cors = require('cors');
const server = require('./server')
let express = require("express");
let app = express();
app.use(limiter)
app.use(helmet())
app.disable('x-powered-by')

app.use(cors({
  origin: '*',//'http://127.0.0.1:3000'
  credentials:true,
  exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept']
}));

app.get('/company/details/', (req, res) => {
  const client = new MongoClient(uri);
  async function run() {
    try{
      console.log("GETTING DETAILS", req.query)
      const database = client.db('company_details')
      const collection = database.collection('details')
      if (!req.query.ticker) {
        res.status(400)
        res.send("Ticker does not exist for details")
      }
      const query = {"ticker": req.query.ticker}
      await collection.find(query)
      .toArray()
      .then(items => {
        console.log(`Successfully found ${items.length} documents.`)
        // items.forEach(console.log)
        res.send(items)
      })
      .catch(err => console.error(`Failed to find documents: ${err}`))
    } finally {
      await client.close()
    }
  }
  run().catch(console.dir)
})

In the App.js of react:

  var companyToCompare = ''
  const setChoice = (choice) => {
    companyToCompare = choice
  }

  const onSubmit = () => {
    console.log('choice', companyToCompare)
    getCompanyDetails(companyToCompare).then(res => {
      console.log("QQQ")
      console.log(res)
    })
    .catch(function(error) {
      console.log("WWW")
    })
  }

<Header/>
<div style={{width: '50%'}}>
   <Select 
     onChange={(choice) => setChoice(choice.label)} 
     options={listOfSP500Tickers} 
   />
</div>
<Button variant="outline-success" onClick={onSubmit} className="mx-1">Add</Button>

The getCompanyDetails code:

const config = {
   // I've tried uncommenting what's in the headers but by doing that all api requests result in CORS issues
   headers:{
      // 'Access-Control-Allow-Origin' : '*',
      // 'Access-Control-Allow-Methods':'*',
      // "Access-Control-Allow-Headers": '*'
      // 'Access-Control-Allow-Credentials': 'true'
   }
};

export function getCompanyDetails(ticker) {
   return axios.get(URL + '/company/details/?ticker=' + ticker, config)
   .then(res => {
      return res
   })
   .catch(function(error) {
      console.log(error)
   })
}

This header component also has an onSubmit function which also calls getCompanyDetails. Strange thing is the Header components call does not trigger CORS issues but the other one does.

My question is what am I doing wrong? Have I not set the CORS header correctly? But if that is the case why is it that the API call works in the <Header/> component but not the other API call? I'm out of ideas

Couple stackoverlow posts I've looked at below, but I've searched through at least 20 other similar posts:

  1. ReactJS: has been blocked by CORS policy: Response to preflight request doesn't pass access control check
  2. Getting error "No 'Access-Control-Allow-Origin' header is present on the requested resource" after Heroku deployment
Mark
  • 730
  • 1
  • 8
  • 22
  • 1
    Is it possible 'helmet' is interfering with these headers? Might be worth turning that off for testing. In the network tab, do you see the request going to the right location? are you seeing any logs server-side as it's trying this? – Evert Feb 12 '23 at 21:15
  • Setting CORS headers on the request side is *ALWAYS WRONG*, so don't even bother adding that to your axios configuration. – Evert Feb 12 '23 at 21:17
  • Thank you Evert, your comment lead me to think outside the box – Mark Feb 13 '23 at 01:05

1 Answers1

0

Thanks to the comment from Evert, I was able to think outside the box. Even though from the console I was getting CORS blocked error the real issue actually came from the express-rate-limit

I had the rate limit set:

const limiter = rateLimit({
    windowMs: 1 * 60 * 1000, // 1 minute
    max: 10, // Limit each IP to 10 requests per `window` 
    standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
    legacyHeaders: false, // Disable the `X-RateLimit-*` headers
})

I anticipated no more than 10 requests a minute on all endpoints but it was exceeding that. Will need to investigate the optimal number of requests a minute but when I increase the max, the CORS error went away.

Mark
  • 730
  • 1
  • 8
  • 22