【问题标题】:Consuming Spring REST API with jQuery使用 jQuery 使用 Spring REST API
【发布时间】:2017-10-24 00:21:39
【问题描述】:

我编写了简单的 Spring REST webapp。现在我想用一些客户端使用我的 API。我决定写jQuery客户端。

我在网上找到了一些例子,所以我尝试了这样的方法:

.html

<head>
    <title>Hello jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="hello.js"></script>
</head>
<body>
    <div>
        <p class="user-id">User id is </p>
        <p class="user-email">His email: </p>
        <p class="user-username">He is known as: </p>
    </div>
</body>

.js

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "http://localhost:8080/api/v1/users/1",
        dataType: "json"
        }).then(function(data) {
            $('.user-id').append(data.userId);
            $('.user-email').append(data.email);
            $('.user-username').append(data.username);
        });
});

"http://localhost:8080/api/v1/users/1" 返回:

{
  "userId": 1,
  "email": "email2@at.pl",
  "password": "haslo123",
  "username": "witek",
  "birthday": "1992-07-12",
  "links": [
    {
      "rel": "self",
      "href": "http://localhost:8080/api/v1/users/1"
    },
    {
      "rel": "shopping-lists",
      "href": "http://localhost:8080/api/v1/users/1/shopping-lists"
    }
  ]
}

但是当我通过 Chrome 打开 html 时,它没有得到任何数据。我做错了什么?

编辑:url:/api/v1/users/1" Chrome 开发控制台喊:jquery.min.js:6 XMLHttpRequest cannot load file:///C:/api/v1/users/1. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

拥有url: "http://localhost:8080/api/v1/users/1" 返回错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

临时解决方案: 发现了一些东西。在 Chrome 上启动我的页面是这样开始的:chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security 使我的页面正常工作。但我不认为这个解决方案。

【问题讨论】:

  • 您可能想了解 CORS。
  • 你是本地失败还是你的rest api在远程主机上?
  • Rest API 在本地。

标签: javascript jquery json spring rest


【解决方案1】:

我会在您的 chrome 开发人员控制台中查看(右键单击检查)并验证网络选项卡是否有错误(如果有)。基本上,检查实际的 url 和网络调用是什么。

【讨论】:

  • 没用,还是No 'Access-Control-Allow-Origin'错误。
  • 既然你只是想学这个,我建议你安装chrome CORS插件google.com/…
  • 是的,这有帮助 ;)
  • 帮助,但使用它,我无法正常使用我的 Facebook 聊天和其他一些页面:/
  • 如何访问 html 文件?我认为问题在于 html 文件不是由 origin: localhost:8080 提供的,这就是导致问题的原因。我的猜测是——如果你将 html 文件移动到你的 springboot 根目录并尝试在那里访问它,那么它们都属于同一个来源
【解决方案2】:

我尝试使用 test.json 中保存的 json(以及指向它的 ajax 调用),它按原样为我工作。

【讨论】:

    猜你喜欢
    • 2012-11-20
    • 2012-09-23
    • 1970-01-01
    • 2018-06-29
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2020-09-12
    相关资源
    最近更新 更多