BrownieCoffee's avatar

error 405 method not allowed QuillJs

Hi everyone.

I use the last version of QuillJS and I would to change the base64 of the image to the URL. I discovered this code to do that :

import Quill from 'quill';

var toolbarOptions = [
    ['bold', 'italic', 'underline'], // toggled buttons  
    [{
        'list': 'ordered'
    }, {
        'list': 'bullet'
    }],
    ['image'], // text direction  
    ['video'],
    ['link'],
];


var quill = new Quill('#editor', {
  modules: {
      toolbar: toolbarOptions,
  },
  placeholder: 'Détaillez nous au mieux votre projet',
  theme: 'snow'
});



  /**
       * Step1. select local image
       *
       */
      function selectLocalImage() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.click();
  
        // Listen upload local image and save to server
        input.onchange = () => {
          const file = input.files[0];
  
          // file type is only image.
          if (/^image\//.test(file.type)) {
            saveToServer(file);
          } else {
            console.warn('You could only upload images.');
          }
        };
      }
  
      /**
       * Step2. save to server
       *
       * @param {File} file
       */
      function saveToServer(file, File) {
        const fd = new FormData();
        fd.append('image', file);
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:3000/creer-un-projet', true);
        xhr.onload = () => {
          if (xhr.status === 200) {
            // this is callback data: url
            const url = JSON.parse(xhr.responseText).data;
            insertToEditor(url);
          }
        };
        xhr.send(fd);
      }
  
      /**
       * Step3. insert image url to rich editor.
       *
       * @param {string} url
       */
      function insertToEditor(url, string) {
        // push image url to rich editor.
        const range = quill.getSelection();
        quill.insertEmbed(range.index, 'image', `http://localhost:3000${url}`);
      }
  
      // quill editor add image handler
      quill.getModule('toolbar').addHandler('image', () => {
        selectLocalImage();
      });




var form = $('form');
$(form).submit(function (e) {
    // Populate hidden form on submit
    e.preventDefault();
    var about = $('input[name=editor]');

    // $(about).value = JSON.stringify(quill.getContents()); 
    $(about).val(JSON.stringify(quill.getContents()));

    //  JSON.stringify($(about));

    console.log("Submitted", $(form).serialize(), $(form).serializeArray());

    // No back end to actually submit to!
    return true;
});

but I have this error

POST http://localhost:3000/creer-un-projet 405 (Method Not Allowed) saveToServer @ app.js:49369 input.onchange @ app.js:49342

Can U help me to fix this error please ?

Thank you by advance !

0 likes
11 replies
Kisiara's avatar

Check if you have this endpoint /creer-un-projet defined in your routes file as POST.

BrownieCoffee's avatar

@kisiara hi yes, sure I use /creer-un-projet for create a post

//my web.php

Route::resource('projets', 'ProjectController')->except('create', 'edit');

Route::get('/creer-un-projet', 'ProjectController@create')->name('post.create');

@aswinghosh I add csdf token into my head

//my home.blade.php

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>GOShr @yield('title')</title>
  <link href="{{ asset('css/app.css') }}" rel="stylesheet">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<!--/head-->

and also inside my post/create.blade.php

@extends('home.home')

@section('main-content')
<main class="main">
    <div class="project-create-form">
        <h3 class="title">Nouveau projet</h3>

        <form class="m" action="{{route('projets.store')}}" method="POST" enctype="multipart/form-data">
            @csrf

            <div class="uk-margin">
                <input class="uk-input" name="title" type="text" placeholder="Titre du projet">

                {{-- @if ($error->has('title'))
                <p>{{$error->first()}}</p>
                @endif --}}
            </div>

            <div class="thumbnail-box">
                <label for="thumbnail" class="thumbnail-label">
                    <i class="fa fa-cloud-upload" aria-hidden="true"></i>
                    ajouter une image thumnail pour votre projet !
                    <input type="file" id="thumbnail" class="thumbnail">
                </label>
            </div>


            <!-- Create the editor container -->
            <div>
                {{-- @if ($error->has('editor'))
                    <p>{{$error->first()}}</p>
                @endif --}}
                <input name="editor" type="hidden">
                <div id="editor">
                </div>
                {{-- <button class="uk-button uk-button-default" type="submit">POSTER</button> --}}

                <button class="uk-button uk-button-default" type="submit">POSTER !</button>
        </form>
    </div>
</main>

@endsection


Kisiara's avatar

Your route is a get but what you are sending from quill is a post

//This is what you have in quill
xhr.open('POST', 'http://localhost:3000/creer-un-projet', true);

A POST endpoint will be expected.

web.php

//This is what you have
Route::get('/creer-un-projet', 'ProjectController@create')->name('post.create');

//This is what is expected
Route::post('/creer-un-projet', 'ProjectController@create')->name('post.create');

Please note the get and post verbs after Route::.

Kisiara's avatar

Well that is now a different error, initially you had a 405. The 419 is caused by CSRF.

Try setting the csrf before sending the request. Like this;

const xhr = new XMLHttpRequest();

const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

xhr.open('POST', 'http://localhost:3000/creer-un-projet', true);

xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);

...

Kisiara's avatar

Can you post the code for sending the ajax request. And if possible the error you are receiving because the issue could now be as simple as missing an application key php artisan key:generate generates one if you don't have one or it could be the token is just not being passed.

BrownieCoffee's avatar

@kisiara

Here, my web.php . I need resource route for my project.

Route::resource('projets', 'ProjectController')->except('create', 'edit');

Route::get('/creer-un-projet', 'ProjectController@create')->name('post.create');


My style.js

      function saveToServer(file, File) {
        const fd = new FormData();
        fd.append('image', file);
        const xhr = new XMLHttpRequest();
        const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
        xhr.open('POST', '/projets', true);
        xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
        xhr.onload = () => {
          if (xhr.status === 200) {
            // this is callback data: url
            const url = JSON.parse(xhr.responseText).data;
            insertToEditor(url);
          }
        };
        xhr.send(fd);
      }

the actual error

VM980:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.xhr.onload (app.js:49366)

Kisiara's avatar

It seems you have come across yet another error. This is no longer the initial 405 or the 419 but seems to be a syntax issue. Can you log the console.log(xhr.responseText) first to confirm the contents. Or just console.log(xhr.response) and see if you can extract your data.

Also, what status are you getting in your network tab? Is it a 200?

BrownieCoffee's avatar

@kisiara Yes I can extract my datas

my style.js

if (xhr.status === 200) {
            // this is callback data: url
            console.log(xhr.response); <==== your suggestion

            const url = JSON.parse(xhr.responseText).data;
            insertToEditor(url);
          }

Please or to participate in this conversation.