Search code examples
javascriptnode.jsrestxmlhttprequestrequest-headers

main.js:295 DELETE http://127.0.0.1:8081/messages/:0 405 (Method Not Allowed) in Javascript


I'm trying to send a restful with JSON Delete request in JavaScript to nodeJS server to delete a message in a chat app. I tried to enable DELETE method through the request headers but it wouldn't work..

How can I enable DELETE method in here?

Here is the client request:

function requestPoll(props) {
            return new Promise(function(resolve, reject) {
                    var xhr = new XMLHttpRequest();
                    xhr.open(props.method, props.action);
                    xhr.timeout = 500; // time in milliseconds
                    if (props.method === 'post') {
                            xhr.setRequestHeader('Content-Type', 'application/json');
                    }
                    xhr.addEventListener('load', function(e) {
                            resolve(e.target.responseText);
                    });

                    xhr.send(JSON.stringify(props.data));

            });
    }

here I send the request:

requestPoll({

                                    method: "DELETE",
                                    action: "/messages/:"+i 

}); 

and the server code:

var http = require('http');
var urlUtil = require('url');
var queryUtil = require('querystring');

var server = http.createServer(function(request, response) {

    var strData,name,index;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "GET , OPTIONS , POST , DELETE ");
    response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");

    if( request.method === 'DELETE' ){ // delete message

        if((url.path).includes("/messages/:")){

                console.log("DELETE");
                index = parseInt( (url.path).substring( (url.path).indexOf(':')+1, (url.path).length ) ); // get message number
                (Babble.messages).splice( index ,1);

        }

    } else {
        response.writeHead(405);
        response.end();
    }

});

Solution

  • I already solved this by correcting the URL. Then it showed OPTIONS. Afterwards I added an if case which treated OPTIONS. Finally I added a response header on nodeJS server side to enable DELETE and the problem was solved.

    Thanks