-1

I'm calling multiple APIs that has CORS pre-flight blocked issue when being call from ReactJS on frontend.

I even tried mode: 'cors' on fetch yet not working.

await fetch(apiURL, {
    method: "POST",
    body: JSON.stringify(body),
    headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        mode: 'cors'
    }
})
.then((responseJson) => {
    console.log(responseJson)
})
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 2
    Have you done any searching on stack overflow or the web? Cors is a security measure. To get around it, you need to make changes to the server not the client. – Evert Jul 24 '23 at 04:59
  • 1
    Does this answer your question? [Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-receive-a-no-access-control-allow-origin-header-i) – nullptr Jul 24 '23 at 05:06
  • @Evert How is CORS a security measure? Surely, you meant "the Same-Origin Policy", not CORS. – jub0bs Jul 24 '23 at 14:10
  • 1
    @jub0bs surely. – Evert Jul 24 '23 at 15:06

1 Answers1

-1

Unfortunatly, CORS has to be handled on server side only. You need to create backend APIs that adds CORS onto the third-party APIs.

Here's an example on NodeJS

sample.js

const express = require('express');
const router = express.Router();
const axios = require('axios');
const cors = require('cors');

router.use(cors());

router.post('/', async function(req, res) {
   try {
      let data = req.body.name
   
      const apiUrl = `https://sample.com/`;
      const headers = {
         Accept: "application/json",
         "Content-Type": "application/json",
      };
      const apiResponse = await axios.get(apiUrl, { headers });
      res.status(200);
      res.send(apiResponse.data);
   }
   catch (error) {
      console.error('Error:', error.message);
      res.status(500).json({ error: 'Something went wrong.' });
   }
});

module.exports = router;

app.js

const express = require('express');
const bodyParser = require('body-parser');

var app = express();
const PORT = 8080;

var sample = require('./sample');

app.use(bodyParser.json());

app.use('/sample', sample);

app.listen(PORT, (error) =>{
    if(!error)
        console.log("Server is Successfully Running, and App is listening on port "+ PORT)
    else 
        console.log("Error occurred, server can't start", error);
    }
);

Packages used: express, body-parser, axios & cors

Rahul Dasgupta
  • 463
  • 8
  • 14
  • Axios makes for a terrible proxy. There are **much better** alternatives like [cors-anywhere](https://github.com/Rob--W/cors-anywhere) – Phil Jul 24 '23 at 06:57