2

I run my project on my Mac OS device and I want to access from another laptop.

the first device gets all responses from the server as well:

http://192.168.1.101:3000/

but another laptop I got this error message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.shadyab.com/api/Api/coupons. (Reason: missing token ‘access-control-allow-origin’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).

const requestOptions = { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', 'Access-Control-Allow-Origin': '*'}, body: JSON.stringify(formData) };

S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

3 Answers3

0

Add

headers: {'Access-Control-Allow-Origin': '*'}

to your server where the API is fetching from

Uday
  • 11
0

I think this is something related to your backend sometimes backend only allows some origins and your new front-end domain must be added to Access-Control-Allow-Origin

but sometimes that could be related to the webserver and its configuration needs to be change, for example if you are using Apache .htaccess file must be changed

Ali Sattarzadeh
  • 3,220
  • 1
  • 6
  • 20
0

Assuming you are using cors() in the backend (like in a node server). Then in your react app, what you can do is setup proxy for the api endpoints.

in the src directory create a file named setupProxy.js. What it does is, create proxies for your api endpoints. What you can do is something like below

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

const BACKEND_HOST = process.env.REACT_APP_BACKEND_HOST || 'localhost';
const BACKEND_PORT = process.env.BACKEND_PORT || 8000;

module.exports = function(app) {

  app.use(
    '/',
    createProxyMiddleware({
      target: target,
      changeOrigin: true,
      logLevel: 'debug'
    })
  );

  /**
  *   You can create other proxies using app.use() method.
  */
};

Note: You do not need to import this file anywhere. It is automatically registered when you start the development server.

And after creating proxies, you should send request to your backend server only specifying the endpoints. Like if you want to send request you should use / instead of http://localhost:8000.

Let me if it works. Thanks

Sifat Amin
  • 1,091
  • 6
  • 15