Git Product home page Git Product logo

Comments (5)

lindyhopchris avatar lindyhopchris commented on August 10, 2024 3

Hi @SirLamer

Sorry for not replying earlier, have been off work. Glad you figured this out and sorry it took a while to discover it.

The 405 is intentional - i.e. if you don't inject a hydrator, the methods that create/update a resource do not effectively exist, which is why I decided to return a 405.

I totally concur though with your point that this actually should be discovered higher up the stack (i.e. don't register the route if it's not allowed), which would then mean that the controller can throw a RuntimeException if it gets hit with a create/update request but hasn't got a hydrator injected. That would have made it a lot easier for you to track down.

I'll link this issue to the routing refactoring issue so that we can incorporate not registering routes into that.

The secondary point is that better documentation would also help. I definitely want to see comprehensive documentation but I think the package needs to settle a bit more before investing the effort in documenting everything fully.

from laravel-json-api.

GregPeden avatar GregPeden commented on August 10, 2024 1

Okay I figured it out.

I created the model and then later chose to allow write actions, so I created the Hydrator but failed to pass it in to the controller constructor as required. The API package checks for this, and in this case it returns the "405 Method Not Allowed" response here:

protected function methodNotAllowed()

I suspect this will happen to others as well, and I propose that "Method Not Allowed" is not the correct response for this error, as this implies the POST/PUT/PATCH methods are intended to be forbidden on the model when the issue is in truth a program error. This code is detecting the exact problem and then returning a misleading response. Furthermore, it does not make use of Laravel's exception handling system, which I spent hours trying to hook to log the event. I only figured this out after searching "methodnotallowed" on the entire package out of suspicion that it's not actually throwing the "MethodNotAllowed" exception.

from laravel-json-api.

GregPeden avatar GregPeden commented on August 10, 2024

Here is my test page to play with the API within Laravel's environment. I am using VueJS and Axios.

@extends('layouts.master')

@section('title')
    @parent :: Sandbox
@stop

@section('content')
<div class="container">
    <div class="row">
        <div class="col-12 my-2">
            CSRF: {{ csrf_token() }}
        </div>
        <div class="col-12 my-2">
            <button class="btn btn-primary" v-on:click="apiTest" :disabled="running">Run <span v-show="running" class="fa fa-spinner fa-spin"></span></button>
        </div>
        <div v-if="response.status" class="col-12 my-2">
            <table class="table table-striped">
                <tr>
                    <td>Status</td>
                    <td>@{{ response.status }} @{{ response.statusText }}</td>
                </tr>
                <tr>
                    <td>Headers</td>
                    <td><pre>@{{ headersPretty }}</pre></td>
                </tr>
                <tr>
                    <td>Data</td>
                    <td><pre>@{{ dataPretty }}</pre></td>
                </tr>
                <tr>
                    <td>Config</td>
                    <td><pre>@{{ configPretty }}</pre></td>
                </tr>
            </table>
        </div>
    </div>
</div>
@stop

@section('vue')
    <script>
        new Vue({
            el: '#app',

            data: {
                running: false,
                response: {
                    data: null,
                    status: null,
                    statusText: null,
                    headers: null,
                    config: null
                }
            },

            computed: {
                dataPretty: function() {
                    return this.response.data ? JSON.stringify(this.response.data, null, 2) : '';
                },

                headersPretty: function() {
                    return this.response.headers ? JSON.stringify(this.response.headers, null, 2) : '';
                },

                configPretty: function() {
                    return this.response.config ? JSON.stringify(this.response.config, null, 2) : '';
                }
            },

            methods: {
                setResponse: function(response) {
                    this.running = false;
                    this.response.data = response.data;
                    this.response.status = response.status;
                    this.response.statusText = response.statusText;
                    this.response.headers = response.headers;
                    this.response.config = response.config;
                },

                resetResponse: function() {
                    this.running = true;
                    this.response.data = null;
                    this.response.status = null;
                    this.response.statusText = null;
                    this.response.headers = null;
                    this.response.config = null;
                },

                apiTest: function() {
                    this.resetResponse();
                    axios
                        .post('{!! route('v1::client-companies.index') !!}',
                            {
                                data: {
                                    type: "client-companies",
                                    attributes: {
                                        name: "API Corp"
                                    }
                                }
                            })
                        .then(function(response) {
                            this.setResponse(response);
                        }.bind(this))
                        .catch(function(error) {
                            this.setResponse(error.response);
                        }.bind(this));
                }
            }
        })
    </script>
@stop

The CSRF token is embedded within all Axios requests like so:

window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};

window.axios.defaults.headers['Content-Type'] = 'application/vnd.api+json';

Every page request includes this for the CSRF token lookup by the client:

<!-- Scripts -->
<script>
    window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
    ]) !!}
</script>

Running the button queries the API and displays the result. The post-execution result is here:
http://codepen.io/gregpeden/pen/BWLGoj

If I run a GET request, it works (I cut out the result in the below result for privacy reasons).
http://codepen.io/gregpeden/pen/yMaQyo

from laravel-json-api.

GregPeden avatar GregPeden commented on August 10, 2024

Actually, I see that the absence of a hydrator is meant to imply that the route is forbidden. It probably should occur earlier in the process, since a lot of code executed, including validation, before it gets to the hydrator check. Probably it should be expected that the designer applies 'only' or 'except' options to the route 'resource()' method, except the $options array is never parsed and so this can't be done at present. This would also improve performance a little bit since Laravel allows the routing table to be pre-compiled and this would reduce the number of routing options it is handling during the URI parsing.

Of course, I am aware that you guys are also exploring refactoring the request/routing design for this package, so this might be moot.

Overall thanks a lot, this is developing in to a great package and it's great to be able to say "our API is JSON spec-compliant so just follow that please".

from laravel-json-api.

lindyhopchris avatar lindyhopchris commented on August 10, 2024

The new routing design has been merged into develop and will be released in v0.8

from laravel-json-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.