Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tptompkins's avatar

Using Dropzone with Spark API

Hey Guys,

I'm trying to upload a file using Dropzone - http://www.dropzonejs.com with a Spark api call but I'm getting a 401 unauthorized error when using Dropzone to make the form post. If I post a form using this.$http.get from Vue to the same route in my api.php routes file, everything works fine. Also, if I include ?api_token=[the token] on the Dropzone post url, everything works fine as well. But it's my understanding that it should still work even if I don't include the token on the url when coming from Javascript.

It appears as though Dropzone doesn't automatically include the necessary authentication info that's needed for the api to work. I know that Spark is using JWT tokens to accomplish this but I'm not really sure how JWT tokens work. It's my understanding that JWT tokens are stored in a cookie, so shouldn't the server still be able to access the cookie in the Dropzone form post?

Any help or explanation as to why I would be getting a 401 unauthorized error when using Dropzone to post a file would be appreciated. Thanks!

0 likes
6 replies
tptompkins's avatar
tptompkins
OP
Best Answer
Level 7

I finally got this working. I noticed that in spark/resources/assets/js/interceptors.js Spark is adding an XSRF-TOKEN to the headers like so:

request(request) {
        request.headers['X-XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN');

        return request;
    }

This interceptor only appears to intercept requests coming directly from Vue so the XSRF-TOKEN wasn't being included in the Dropzone post request headers. Dropzone allows you to send additional headers in the Dropzone configuration so I added the XSRF-TOKEN to the Dropzone posts like so:

Dropzone.options.myDropZone = {
          url: "/api/route-path",
          method: "post",
          headers: { 'X-XSRF-TOKEN': Cookies.get('XSRF-TOKEN') },
     [...other config options]
};

After adding the token to the post headers, the 401 Unauthorized error went away. Hopefully this helps somebody else!

Tommy

9 likes
davejitsu's avatar

Whew.I was about to start my deep dive into Spark to figure out why I was getting the same error. Thank you!

Tjohnson909's avatar

I encountered a similar obstacle with a different javascript package. This saved the day!

Please or to participate in this conversation.