Thursday 8 June 2017

Post ajax request send a options request instead of a post

I'm sending a post ajax request:

var responsehttpreq = {}
function createAndSendXmlHttpReq(){
    requestBody = {
        hostname: "prova",
        pathname: "prova",
        query: "prova",
        method: "prova"
    }
    console.log("Siamo nella funzione createAndSendXmlHttpReq")
    var req = new XMLHttpRequest()
    req.onreadystatechange = handler
    req.open("POST","http://localhost:8080",true)
    req.setRequestHeader("Content-type","application/json")
    req.send(JSON.stringify(requestBody))
}

function handler(){
    if(this.readyState == 4 && this.status == 200){
        console.log('----Risposta http------')
        console.log('Status Code:'+this.status)
        console.log('Dati:'+this.response)
        responsehttpreq = JSON.parse(this.response)
    }
}

The createAndSendXmlHttpReq() is called from a button in a html page, when I press the button I don't recive any response, but I can see from the developer console that an option request has been send, for the CORS option. I have implemented a node js server that in case of an options request send a properly response:

if(req.method == "OPTIONS"){
        res.setHeader("Access-Control-Allow-Origin","*")
        res.setHeader("Access-Control-Allow-Methods","POST")
        res.setHeader("Access-Control-Request-Headers","content-type")
        res.end()
    }

The browser receive a 200 ok response from the server for the options request, but after that my ajax post request don'arrive to the server. What is the problem?



via SimCor

No comments:

Post a Comment