-1

i'm using an external api, i setup express.js as my backend and have app.use(cors()) to get around cors policy error but im still getting the error when im trying to make an api call in react

server setup

server.js

const express = require('express')
const app = express();
const cors = require('cors')

app.use(cors({
    origin: '*'
}));

const port = 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

API call

app.js

  useEffect(() => {
    async function datareciever() {
      const response = await fetch("api_url")
      const data = await response.json()
      console.log(data)
    }
    datareciever()
  }, [])

error that I'm receiving in the browser

Access to fetch at 'api_url' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

I've also tried setting the port to 3000, but the express server takes up port 3000 so react then switches to 3001.

I believe origin: '*' should allow for any port/domain, so I don't think that could be the issue.

Current file structure(if it matters). React is inside expressapp folder.

enter image description here

What could be causing the issue?

devAR
  • 349
  • 7
  • 21
  • 1
    Share the full error – Evert Sep 12 '21 at 04:43
  • Your problem seems similar to - https://stackoverflow.com/questions/34644622/how-to-manage-cors-policy-properly-in-express Try this - https://stackoverflow.com/a/56051528/5417843 – shri_world Sep 12 '21 at 04:47
  • @Evert updated post to included full error – devAR Sep 12 '21 at 04:48
  • Is `api_url` in your `app.js` replaced with the actual URL of the external API or is this replaced with your API URL? – Michael Pu Sep 12 '21 at 04:58
  • @MichaelPu **api_url** is the url for the external api with a header for the API key, just removed it and put **api_url** to post it here because the actual URL is a bit long, just makes the post look neat. – devAR Sep 12 '21 at 05:08

1 Answers1

0

The problem is that the external API URL that you're using does not support CORS. So you are not able to send a request to that external API directly from your React code. However, you can use your Express.js backend to forward your request to the external API. You can read more about CORS here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

To use the Express.js backend as a proxy to forward your request to the external API, you can use the http-proxy package.

For server.js

const express = require('express')
const app = express();
const cors = require('cors');

const proxy = require('http-proxy').createProxyServer({
    host: 'external_api_url',
});

app.use(cors({
    origin: '*'
}));

const port = 5000;

app.get('/external_api', function(req, res, next) {
    proxy.web(req, res, {
        target: 'external_api_url'
    }, next);
});

app.listen(port, () => console.log(`Server started on port ${port}`));

For app.js

  useEffect(() => {
    async function datareciever() {
      const response = await fetch("localhost:5000/external_api")
      const data = await response.json()
      console.log(data)
    }
    datareciever()
  }, [])
Michael Pu
  • 357
  • 1
  • 4