Why isn't my Fetch request sending custom headers in React-Native?

Viewed 1316

I am calling a fetch request akin to this.

fetch('https://api-endpoint.com/api',
        {
            method: "POST",
            headers: new Headers({
                'custom-header': 'custom header value'
            })
        }
     )
    .then(res=>{
        /* code */
    })
    .catch(err=>{
        /* code */
    })

But it seems that the header is not being sent to the server. The server runs on Node.js, and I am attempting to reach it with React-Native.

I have allowed "access-control-allow-origin": "*" on the server, but to no avail.

I can also reach other endpoints on the server that don't require any headers.

And lastly, I have set the headers with both new Headers() and as an object.

What exactly am I missing to allow the headers to be sent? Is there a way to see exactly what is going on with my request in react-native?

It works in postman just fine.

EDIT:

I am using the cors middleware in my server.

app.use(cors())

appConfig.init(app);
2 Answers

Can you add these lines before using routes and try?

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");

  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization, custom-header"
  );

  res.header("Access-Control-Expose-Headers", "custom-header");

  next();
});

And if you are using express cors middleware, you can add allowedHeaders and exposedHeaders options.

https://github.com/expressjs/cors#configuration-options

note if these configuration replaces the default headers, you may need to add the default headers to the options.

app.use(
  cors({
    exposedHeaders: ["custom-header"],
    allowedHeaders: ["custom-header"]
  })
);

Lastly you had better to use fetch api like this to send headers:

fetch('https://api-endpoint.com/api',
  {
    method: "POST",
    headers: {
      "custom-header": "custom header value"
    }
  }
)
  .then(res => {
    /* code */
  })
  .catch(err => {
    /* code */
  })

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Be sure,you added the header in:

res.header( "Access-Control-Allow-Headers", "Your_OWN_header,...." );

Related