Lokesh Pandey
Lokesh Pandey

Reputation: 1789

Issue regarding posting a request using ajax

I am new to ajax and jquery. And I have gone through few threads regarding the issue I am getting on SO, but didn't get any problem resolved. I am getting two errors over here.

OPTIONS http://localhost:8082/xxx/xxx/xxxx 404 (Not Found)

Failed to load http://localhost:8082/xxx/xxx/xxxx: Response for preflight does not have HTTP ok status.

Here is my simple code

$.ajax({
    url: url,
    crossDomain: true,
    type: "POST",
    data: JSON.stringify(queryData),
    contentType: "application/json"
}).done(function(msg){
    $("#thank_you_comment").text("Thank you");
    $("button").text("GOT IT");
    queryData.id = msg.id
    $.ajax({
        url: another_url,
        crossDomain: true,
        type: "POST",
        data: JSON.stringify(queryData),
        contentType: "application/json"
    }).done(function(message){
        event.preventDefault();
        console.log(message);
        return;
    });
});

The second ajax call I am making is local one on vertx. And I am very much sure that another local server is up and running.

But I am not sure why I am getting the not found error.

Any help would be highly appreciated.

Upvotes: 1

Views: 1006

Answers (1)

Lokesh Pandey
Lokesh Pandey

Reputation: 1789

Thank you for the above comments which help me to understand the problem. To resolve this error what I did rather than directly posting the request from client side, I send the request to server side and then invoking the request from server side which completely eliminates the CORS issues and gives more control on the data.

From client side, I did this

$.ajax({
        url: /post/request-to,
        type: "POST",
        data: JSON.stringify(queryData),
        contentType: "application/json"
    }).done(function(message){
        event.preventDefault();
        console.log(message);
        return;
    });

And then in the server script

app.post('/post/request-to', function(req, res){
    try{
        request.post({
            headers: {'content-type' : 'application/json'},
            url: "http://some/url",
            body: JSON.stringify(req.body)
        }, function(error, response, body){
            if(error){
                console.log("Error: "+error)
            }else{
                res.send(body)
            }
        });
        console.log(req.body);
    }catch(err){
        console.log(err)
    }
});

Upvotes: 1

Related Questions