0

I need some help with fetching data, it said blocked by CORS policy, I've tried to install chrome extension that allowed CORS, but it was still error, I've tried by POSTMAN, the API respond correctly, I've tried using axios, it was still error, I've tried change "Access-Control-Allow-Origin": "*" to "Access-Control-Allow-Origin": "http://localhost:3000", it was still error, i think my problem is in "Access-Control-Allow-Origin": "*", I really appreciate your help.. thank you..

fetch("https://api.rajaongkir.com/starter/province", {
  method: "GET",
  headers: {
    key: myKey,
    "Access-Control-Allow-Origin": "*"
  }
}).then(res => {
  console.log(res);
});

here the response capture response capture

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Moh Jonaidy
  • 75
  • 1
  • 10
  • 1
    `Access-Control-Allow-Origin` is a ***response*** header. You don't get to tell a site to allow you to access its content. – zero298 Dec 16 '19 at 19:08

1 Answers1

-2

Cors issues are tough, and without knowing what your backend looks like, it's hard to tell what problem you are having. Here is an alternate solution that doesn't include keys. This problem will only exist in your development environment UNLESS you are separating your backend and frontend on separate domains ie (www.frontend.com and www.backend.com).

In your front end you can do this,

headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    "Access-Control-Allow-Credentials": true,
                }

Then in your backend you can do this::

app.use(
    cookieSession({
        name: "session",
        keys: [keys.COOKIE_KEY],
        maxAge: 24 * 60 * 60 * 100
    })
);

router.use(function (req, res, next) {
    res.set("Access-Control-Allow-Origin", 'http://localhost:3000/'); 
     res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
     res.header("Access-Control-Allow-Credentials", true);
     res.header
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With, access-control-allow-credentials");

Basically this is CORS telling you that it only takes CROSS ORIGIN DOMAIN requests from whatever you specify in your backend. Try this and let me know.

lakerskill
  • 1,019
  • 1
  • 11
  • 24