-1

I want to make HTTP Post request to external API, but as I'm trying to do it from React with axios I have a CORS error (No 'Access-Control-Allow-Origin' header is present on the requested resource). At the same time while making this request in .NET everything seems to be ok. I don't have a clue why is it working like this, so maybe someone can figure it out.

React request:

var bodyFormData = new FormData();
    bodyFormData.append('key', 'apiKey');
    bodyFormData.append('function', 'getTeams');

    async function fetchData() {
        await axios({
            url: 'https://external.api/api/',
            method: 'POST',
            data: bodyFormData,
            withCredentials: true,
            headers: {
                'Content-Type': 'multipart/form-data',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
                'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
            },
        })
            .then((response) => {
                console.log(response)
            })
            .catch((err) => {
                console.log(err)
            });
    }
    fetchData();

.NET request:

var request = (HttpWebRequest)WebRequest.Create("https://external.api/api/");

        var postData = "key=apiKey";
        postData += "&function=getTeams";
        var data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
axern
  • 47
  • 9
  • 1
    CORS is a security measure that only applies to browsers. Your backend code is exempt from this, because there's no browser to enforce it. – abdusco Jul 29 '21 at 08:00
  • 1
    Also, you can't send those headers (`Access-Control-*`) yourself. They must be returned by the API to indicate that you are allowed to send those requests. – abdusco Jul 29 '21 at 08:01
  • Oh okay, I can undarstand, so as i thought, the simplest solution will be to use .NET app as proxy and then allow cross-origin communication between .NET and React apps? – axern Jul 29 '21 at 08:03
  • 1
    Exactly like so – abdusco Jul 29 '21 at 08:03
  • Thank you very much then, I will make it this way. – axern Jul 29 '21 at 08:04

1 Answers1

2

CORS is a security measure that only applies to client side (browser). Browsers send Origin header whether you want it or not, and it's checked by the API to decide if it should serve you (by allowing the browser to go on with the main request).

You can send the request from the backend without issues, because there's no Origin header to speak of.

So you have two options:

  • Proxy the API call from your backend
  • Ask API to allow requests from the app's origin https://$domain:$port.

If the API is in your control, this should be easy, if not, proxying is a more straightforward solution.

References

abdusco
  • 9,700
  • 2
  • 27
  • 44