0

I'm trying to make a GET request to the url "https://public-api.wordpress.com/wpcom/v2/work-with-us" with special header 'X-future' and value 'automattician'. However, I get the error that this header is not allowed in preflight response:

"Request header field x-future is not allowed by Access-Control-Allow-Headers in preflight response."

From searching around, it seems that this is a CORS issue and I have to add the header from the server side. However, I don't have access to the server.

Is this problem not solvable or am I missing something? Here's what I wrote in code pen to test:


  let url = 'https://public-api.wordpress.com/wpcom/v2/work-with-us';
  const options = {
        method: 'GET', //default
        headers: {'X-future': 'automattician'}
    };

  fetch(url, options)
  .then(blob => blob.json())
  .then(data => console.log(data));

Joe Liang
  • 105
  • 1
  • 6
  • You could write a browser extension to alter the response headers, or a proxy server that will add this header in its reponses – kmaork Feb 29 '20 at 20:04

1 Answers1

1

You can get around these cors issues by running the fetch on your own server or serverless function.

Running this in a node script will work and allow you to pass the results back to your website.

const fetch = require("node-fetch");

function fetchServer() {
  return fetch("https://public-api.wordpress.com/wpcom/v2/work-with-us", {
    headers: { "X-future": "automattician" }
  })
    .then(res => res.json())
    .then(res => res);
}

You can easily deploy this using a serverless function, sometimes called lambda in AWS but most cloud providers have something similar https://aws.amazon.com/lambda/

Evan Hennessy
  • 197
  • 1
  • 6
  • Does this mean I have to set up a proxy server? If I understand correctly, the proxy server makes the actual fetch and stores the result and I just retrieve the result from my proxy server? Can you explain why the custom header is allowed if requested from a proxy server instead of from localhost or from my website? – Joe Liang Feb 29 '20 at 21:33
  • Nevermind, I figured it out. For anyone else reading this, I just wanted to know what fetch returned so I used npm to install node-fetch, saved the above code in a file without enclosing it in a function, and call "node [file]" on the CLI. Guess the trick is using fetch from server-side – Joe Liang Feb 29 '20 at 22:52