I'm having a problem with the request to my API from my program in C#, it's giving me a CORS error (From the web it works because my local IP it's in the whitelist, but from the program it gives me an error the cors request).
The api is created in Express.
My Cors:
const dominiosPermitidos = [url];
const corsOptions = {
origin: function(origin, callback) {
console.log(origin);
if (dominiosPermitidos.indexOf(origin) !== -1) {
//El origen del request esta permitido
callback(null, true);
} else {
callback(new Error('No permitido por Cors'))
}
}
}
app.use(cors(corsOptions));
The call in c#:
url = "127.0.0.1/api/datos";
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
Stream myStream = myHttpWebResponse.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myStream);
//Leemos los datos
string Datos = HttpUtility.HtmlDecode(myStreamReader.ReadToEnd());
dynamic data = JsonConvert.DeserializeObject(Datos);
return data;
Error c# error
Error api error
Should I deactivate Cors?
Thanks
I tried to put my local ip in the whitelist, but when i call the API from my C# program the CORS gives me an error
CodePudding user response:
Your C# program doesn't seem to be sending an origin, which is fine since it's not a browser. But since your server is configured to error early if CORS is going to block the response from reaching the browser, you're getting an error back from it (which you normally wouldn't be able to read if it was from a browser).
If you look at https://www.npmjs.com/package/cors in the section "Configuring CORS w/ Dynamic Origin", you'll see that they put a " || !origin" in the second example for this very reason, so the server continues processing it if it's from a server. So you should be able to just change your Node.js server code like this:
const dominiosPermitidos = [url];
const corsOptions = {
origin: function(origin, callback) {
console.log(origin);
if (dominiosPermitidos.indexOf(origin) !== -1 || (! origin)) {
//El origen del request esta permitido
callback(null, true);
} else {
callback(new Error('No permitido por Cors'))
}
}
}
app.use(cors(corsOptions));
You might also find this helpful: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Hope this helps.
Edit: since I can't write comments I'll have to do it here. You could disable CORS on the server, but that will mean your website on that other origin won't be able to send requests. But I might have misunderstood and you might not ever be sending requests to the API from the browser, in which case you can just remove all the CORS logic.