CROS OPTIONS request when trying to upload a file with $http angularjs
<p>I'm actually trying to implement a file upload system between my client side angularjs app and my server but i'm having difficulties to implement this feature.
The problem seems to come from the preflight OPTIONS request sent from Chrome.</p>

<p>When I test my route with postman everything work just fine.
Here is a few screen shots of the postman request execution:</p>

<p><a href="http://i.stack.imgur.com/hwu5T.png" rel="nofollow">First part of postman example</a></p>

<p><a href="http://i.stack.imgur.com/HUjE7.png" rel="nofollow">Second part of postman example</a></p>

<p>As you can see the route has two parameters a library id and a file to be uploaded and an authentification token.</p>

<p>The problems appear when I try to implement an upload feature in my angular web app.Indeed when I call my $http post request a OPTIONS preflight request is sent to my server.This OPTIONS request doesn't seem to have any of the parameters given to the post request it precedes making my authentification middleware (that has the function of validating the user/token) on my server side respond with a 401 error.</p>

<p>More exactly:</p>

<blockquote>
  <p>XMLHttpRequest cannot load .....  Response for preflight has invalid http status code 401</p>
</blockquote>

<p>It seems that those preflight request are made by the browser when say detect a cross origin resource sharing. This is were I hit a brick wall. I cannot seem to understand how to:
- either send the token with the options request to validate this request
- or to bypass this options request to directly send my post request. </p>

<p>my upload function looks like this:</p>

<pre><code> $http({
        method: 'POST',
        url: 'my-upload-url',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        data: {
            library: my-library-id,
            file: my-file-to-upload,
            token: user-authentification-token
        },
        transformRequest: function (data, headersGetter) {
            var formData = new FormData();
            angular.forEach(data, function (value, key) {
                formData.append(key, value);
            });

            var headers = headersGetter();
            delete headers['Content-Type'];

            return formData;
        }
    })
    .success(function (data) {

    })
    .error(function (data, status) {

    });
</code></pre>

<p>My questions are:</p>

<ul>
<li>Is there a way to actually send my user token in the OPTIONS request to make it valid server side?</li>
<li>Is there a way of formatting my post request (header/data/params) to make it bypass this preflight browser request?</li>
<li>Is the formatting of my post request wrong in any way making it trigger the OPTIONS request from Chrome?</li>
</ul>

<p>Thank you in advance for your help.</p>

<p>Martin</p>