简体   繁体   中英

jQuery $.post method results in 405 (Not Allowed) error

I have a website served up using Nginx. I've create a very simple web-page with ap tag to display the contents of a file, test.html. I have two buttons, one that does a GET request using $.ajax, and one that does a POST request using $.post.

The GET request works fine, and the contents of the file test.html display in my p tag. When I try to POST to that same file, however, I get an error in the console: "Failed to load resource: the server responded with a status of 405 (Not Allowed)". The POST request is pretty simple, taken right from the example on W3Schools.com - https://www.w3schools.com/JQuery/jquery_ajax_get_post.asp . So I am baffled.

I tried to read and understand what a 405 error could mean. Presumably it means that the POST request is not supported by this URL. But how would I enable it to be supported?

    <p id="content-from-ajax"></p>

    <button id="get-content-btn">Get Content</button>

    <button id="post-something-btn">Post something</button>

    <script type="text/javascript">
        $("#get-content-btn").click(function() {
            $.ajax({type: "GET", 
                    url: "test.html", 
                    success: function(result) {
                        $("#content-from-ajax").html(result);
                        alert("GET successful");
                    }
                   });
        });

        $("#post-something-btn").click(function(){
            alert("GRRRR");
            $.post("test.html",
                   {
                name: "Donald Duck",
                city: "Duckburg"
            },
                   function(data, status){
                alert("something worked");
            });
        });
    </script>

For a POST request to access resources hosted on your web server you will need an application server. Examples include Laravel for PHP, Spring for Java, and Node for JavaScript.

Many application server require you to explicitly specify what type of request a particular endpoint can receive, this can be confusing when learning a new web application framework because a GET request is often the default.

Though a POST request must be handled by an application server it doesn't need to be one your hosting. So you can access public APIs with a POST request (depending on the API and the endpoint your using) without hosting your site on an application server. So if this project is purely educational, this is the best way to test using a POST request without going through the trouble of configuring one yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM