-1

I am trying to call APIs to the popular servers like OwnCloud, Openfire, and Ejabberd which are installed in my local server. I am creating a ReactJS website. Initially, I used the fetch() method to access the API. But I am getting the CORS error as the result.

Access to fetch at 'http://x.x.x.x:8088/api/contacts/3000@x.x.x.x' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.

I checked the same APIs using Postman and successfully got the response. Then I tested it with the node code below using the command line and got the API response in the command line.

var http = require("http");

var options = {
  "method": "GET",
  "hostname": "x.x.x.x",
  "port": "8088",
  "path": "/api/contacts/3000@x.x.x.x",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "e5a6f2bb-abc9-8ce7-f237-342ab53ab9d6"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

I implemented the same node code into my ReactJS code and getting the same CORS error again.

I've added the below headers to the fetch() method's header and getting the same CORS error.

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
'Access-Control-Allow-Headers': 'origin, content-type, accept, authorization',

I added mode: "cors" into the fetch() method. But still same error.

Could you please provide a solution to avoid this *CORS* issue?

KIRAN K J
  • 632
  • 5
  • 28
  • 57
  • 1
    Maybe this solution works for you. https://stackoverflow.com/questions/25727306/request-header-field-access-control-allow-headers-is-not-allowed-by-access-contr – Chance Jan 18 '19 at 05:53

1 Answers1

1

You have to create a local proxy for API calls.

Here, proxy uses url pattern to match to the api calls and redirecting them to the corresponding server.

Try with the following:

  • Install http-proxy-middleware

    npm install http-proxy-middleware --save
    
  • create src/setupProxy.js

    const proxy = require('http-proxy-middleware');
    
    module.exports = function(app) {
    
       app.use(proxy('/api', { target: 'http://localhost:8088/' }));
    
    };
    
  • Then run your local Dev server

Rakesh Makluri
  • 647
  • 4
  • 10