Yanick Rochon
Yanick Rochon

Reputation: 53526

CORS origin always undefined when fetching data

Using this server configuration

import Cors from 'cors';

const cors = Cors({
   methods: ['GET', 'POST', 'HEAD'],
   allowedHeaders: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Api-Authorize, X-Authorize',
   credentials: true,
   origin: (origin, callback) => {
       console.log("*** TESTING", origin);

       return callback(null, true);  // debug, otherwise nothing works
   },
   optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
});

const applyCors = async (req, res) => new Promise((resolve, reject) => {
   cors(req, res, (result) => {
      if (result instanceof Error) {
         reject(result);
      } else {
         resolve(result);
      }
   });
});

export const apiMiddleware = handler => async (req, res) => {
   await applyCors(req, res);

   // ... req is extended with utils    

   return handler(req, res);
};

And a client fetch request like

const response = await fetch(`/api/data`, {
   credentials: 'same-origin',  // also tried "include"
   headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-Api-Authorize': 'secret'
   },
   method: 'GET'
});

The server console.log always prints

*** TESTING undefined

When inspecting the request, I see the X-Api-Authorize header, but not Origin. What's missing?

Upvotes: 0

Views: 777

Answers (1)

Quentin
Quentin

Reputation: 943220

fetch(`/api/data`

That's a relative URL, so you are making a same-origin request.

The origin header is only included in cross-origin requests.

(That's a simplification, as jub0bs points out, there are other times it will be included, but your code doesn't meet any of those conditions).

Upvotes: 3

Related Questions