1

I'm currently trying to implement an API for my company's web application, and I want to be able to make GET and POST requests to their endpoints to retrieve and add information. I tried it to make these requests first in Postman to make sure that our apikey worked properly, and the requests were successful. So I figured I would start out small and create a jsFiddle before actually implementing it inside our web application, but I ran into a little problem. When I tried running my jsFiddle code I ended up with the error "Access to XMLHttpRequest has been blocked by CORS policy"

I don't know much about axios and whether or not you can even use API keys within their requests, but an API key is required for me to retrieve any information from the different endpoints.

If anyone could help me understand where I'm going wrong that would be much appreciated, thanks.

My fiddle

const url = "https://someurl/api/ping"
const apiKey = "MY-KEY"

axios.get(url, {
    headers: {'X-API-KEY': apiKey}
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

I expected to get a response from this, but all I get is that error code. Works fine in Postman, but I'm using JSON as the raw body, so I'm not sure why axios won't work.

Michael
  • 1,454
  • 3
  • 19
  • 45
  • 1
    Though that answer has good information, it still doesn't answer my question about whether or not I'm doing this correctly with an API key. – Michael Oct 08 '19 at 19:13
  • That is how you set a `header`. How any _API Key_ is sent depends on how the application designers expect it. – whodini9 Oct 08 '19 at 19:59
  • @whodini9 that's not how you set the API Key in Axios because Im getting the same error. That doc does nothing to address the question he asked. Im sending requests through Postman that succeed but still fail when run through Axios because they have a bug with the X-Api-key header. It does not get passed with the rest of the request headers. – lopezdp Jan 23 '21 at 14:54

0 Answers0