代码之家  ›  专栏  ›  技术社区  ›  Lokesh Pandey haseeb

关于使用Ajax发布请求的问题

  •  1
  • Lokesh Pandey haseeb  · 技术社区  · 7 年前

    我不熟悉Ajax和jQuery。关于我正在讨论的问题,我已经讲了几条线索,但是没有解决任何问题。我这里有两个错误。

    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.
    

    这是我的简单代码

    $.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;
        });
    });
    

    我正在进行的第二个Ajax调用是Vertx上的本地调用。我非常确定另一台本地服务器正在运行。

    但我不知道为什么我会得到未找到的错误。

    任何帮助都将不胜感激。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Lokesh Pandey haseeb    7 年前

    感谢您的上述评论,这些评论有助于我理解问题。为了解决这个错误,我没有直接从客户端发布请求,而是将请求发送到服务器端,然后从服务器端调用请求,这完全消除了CORS问题,并提供了对数据的更多控制。

    从客户的角度来看,我做到了

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

    然后在服务器脚本中

    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)
        }
    });