AJAX返回net :: ERR_CONNECTION_REFUSED

时间:2016-10-01 05:39:51

标签: ruby-on-rails ajax curl rails-api

我正在使用RAILS API。

当我从终端呼叫时,它给出了正确的结果。现在我试图从外部应用程序调用该API。

CURL:

curl -H 'Accept: application/vnd.marketplace.v1' http://api.market_place_api.dev:3000/users/1

关于CURL正常运作。

现在我的外部文件是代码:

1234.html

<!DOCTYPE html>
<html>
    <head>
        <title>API Testing</title>
        <script src="https://code.jquery.com/jquery-2.2.4.min.js" crossorigin="anonymous"></script>

        <script type="text/javascript">
            $.ajax({
                headers: { Accept : "application/vnd.marketplace.v1"},
                url: "http://api.market_place_api.dev:3000/users/1",
                type: 'GET',
                contentType: 'application/json',
                data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"},
                success: function (data) {
                    alert(JSON.stringify(data));
                    $('div.jsonoutput').append(JSON.stringify(data));
                },
                error: function(){
                    alert("Cannot get data");
                }
            });
        </script>
    </head>

    <body>
        <div><center><p><strong>API Request &amp; Response Testing</strong></p></center></div>

        <div class="jsonoutput"></div>

    </body>
</html>

1 个答案:

答案 0 :(得分:0)

将这些行添加到application_controller

<强>控制器:

protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' }
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

<强>脚本:

    <script type="text/javascript">
        $.ajax({
            url: "http://api.market_place_api.dev:3000/users/1",
            type: 'GET',
            contentType: 'application/json',
            data: { auth_token: "Vb6BQdPQNx9uD_wczkeW"},
            success: function (data) {
                alert(JSON.stringify(data));
                $('div.jsonoutput').append(JSON.stringify(data));
            },
            error: function(){
                alert("Cannot get data");
            }
        });
    </script>