Haider Ali
Haider Ali

Reputation: 1121

File upload with fetch API vuejs returns 419 unknown status

I am using VUE.js with Laravel to upload file using fetch api. I have added the csrf token to the header of the request, but still getting the 419 unknown status. Any help will be appreciated thanks.

Here is the JS of the component

<script>
    export default {
        name:'UploadModal',
        data(){
            return {
                image:'',
                ext:'',
                file:''
            };
        },
        methods: {
            onFileChange(e) {
                var files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.file = files[0];
                this.createImage(files[0]);
            },
            uploadArtwork: function () {
                let formData = new FormData();
                formData.append('artwork', this.file);
                fetch(this.$parent.itemUrl, {
                    method:'POST',
                    body: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'X-CSRF-TOKEN' : Laravel.csrfToken
                    }
                })
                    .then(res => res.json())
                    .then(res => {
                        alert(res);
                    })
                    .catch(e => console.log(e));
            },
            createImage(file) {
                var image = new Image();
                var reader = new FileReader();
                var vm = this;

                reader.onload = (e) => {
                    vm.image = e.target.result;
                };
                reader.readAsDataURL(file);
            },
        }
    }
</script>

Upvotes: 1

Views: 1916

Answers (1)

JPark
JPark

Reputation: 789

I know this is an old question, but I ran into this issue as well when using fetch and the linked answer (Laravel 5.5 ajax call 419 (unknown status)) did not help, since that relates to jQuery's Ajax method.

For those who are facing the same issue, it looks like this is due to the default credentials setting (defaults to "omit"), which essentially omits the csrf header for some reason. You can get around this by changing credentials to "same-origin" or "include" depending on your needs.

Example:

fetch("/leads", {
        method: 'POST',
        credentials: "same-origin",
        headers: csrf_header
    }).then(res => res.json())
    .then(
        (json) => {
            this.setState({
                isLoaded: true,
                items: json.leads.data,
                sort: json.sort,
                search: json.search,
                sort_by: json.sort_by,
                filter: json.filter
            });
        }
    );

Upvotes: 1

Related Questions