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: