-1

Great explanation on CORS No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

I created a local asp.net mvc app using C# (httpclient) to POST to an API on a server that is set up to allow CORS and it works. But the javascript app I'm running locally returns the following:

Access to XMLHttpRequest at 'https://apiurl/auth/token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET requests work in the js app. Here is a snippet of code:

axios({
  method: 'post',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
  },
  baseURL: 'https://apiurl',
  url: '/oauth/token',
  data: {
    grant_type: 'password',
    username: this.state.username,
    password: this.state.password
  }
}).then(resp => {
  console.log(resp);
});

API is WEBAPI with CORS enabled.

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I also understand proxying is a potential solution, but I am curious to know if I am missing something here.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
asunrey
  • 875
  • 2
  • 10
  • 28
  • What’s the HTTP status code of the response to the request? Use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success message? I’m guessing it’s likely a 400 Bad Request error. – sideshowbarker Jun 13 '19 at 02:00
  • Yes, 400 Bad Request – asunrey Jun 13 '19 at 02:17
  • 1
    Check the server logs on the server side of the server you're sending the request to. Look at whatever messages the server is logging there which indicate why the POST isn't working, and so causing the server to end up sending that 400 response. Your frontendhe POST request you're sending from your frontend JavaScript code isn't formatting the POST request in the way the server expects. – sideshowbarker Jun 13 '19 at 02:26
  • 2
    You need to supply Axios with the correct data format if you're not sending JSON. – Phil Jun 13 '19 at 02:41
  • ok, moved me forward, thank you both. I now get a 200, the json needed to be in querystring format. Now receiving the same error mentioned, but with 200 and the following warning: VM278:1 Cross-Origin Read Blocking (CORB) blocked cross-origin response apirurl/auth/token with MIME type application/json – asunrey Jun 13 '19 at 03:34
  • sideshowbarker has great explanations on how this works. And my last problem is explained in the details: https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – asunrey Jun 13 '19 at 04:08

1 Answers1

0

Try to set Access-Control-Allow-Origin as https://apiurl, and set withCredentials as true.

jkdev
  • 11,360
  • 15
  • 54
  • 77
Heekei
  • 45
  • 1
  • 7