1

(AXIOS GET)

I am requesting .net core web api 2.1 with react native, but the error I get on the console as follows:

Note: Cors was granted permissions by .net core 2.1.

Code:

return axios.get('http://127.0.0.1:50000/api/values', {
  credentials: 'include'
})
.then(
  (response) => {
    console.log(response);
  }
)
.catch(
  (error) => {
    console.log(error);
  }
);

Error:

Error: Network Error
    at createError (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\axios\lib\core\createError.js:16)
    at XMLHttpRequest.handleError (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\axios\lib\adapters\xhr.js:87)
    at XMLHttpRequest.dispatchEvent (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\event-target-shim\lib\event-target.js:172)
    at XMLHttpRequest.setReadyState (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:580)
    at XMLHttpRequest.__didCompleteResponse (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:394)
    at D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:507
    at RCTDeviceEventEmitter.emit (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190)
    at MessageQueue.__callFunction (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349)
    at D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106
    at MessageQueue.__guard (D:\Projeler\Mobile\ReactNative\primCepte\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297)
c-chavez
  • 7,237
  • 5
  • 35
  • 49
Onur İnci
  • 118
  • 1
  • 8

1 Answers1

0

Just had the same problem.

Even though you don't get CORS error you might still be missing Access-Control-Allow-Origin header which still 'erors' your request.

You need to add CORS to your ASP.net core app.

services.AddCors(options =>
    options.AddPolicy("MyPolicy",
        builder => {
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        }
    )
);

and then

app.UseCors("MyPolicy");

before

app.UseMvc();

This is convenient and will allow ANY ajax request to your API, but its not ideal.

You can allow IP's and domains of your choosing. How to do that read more in Enable Cross-Origin Requests (CORS) in ASP.NET Core

ColdHands
  • 947
  • 8
  • 28