【问题标题】:make a javaScript call to consume REST API running on localhost进行 javaScript 调用以使用在 localhost 上运行的 REST API
【发布时间】:2020-08-07 21:18:04
【问题描述】:

我有一个 java-springboot 微服务在端口 8080 和 localhost 服务器上运行。它看起来像这样:

@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = "")
    public User getUser() {
        return userService.getUser();
    }
}

我正在尝试使用调用“http://localhost:8080/user”访问用户数据。通过浏览器和 Postman 对其进行测试时,调用正在返回数据。但是使用 javacript 它返回一个空响应。

我是 js 的新手。

我的 javascript 代码如下所示:

function getCurrentUser()
{
    try
    {
        var userUrl = "http://127.0.0.1:8080/user";
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            try
            {
                if (this.readyState == 4 ) {
                    var response = this.responseText;
                    document.getElementById("idCurrentName").innerHTML = response;              
                }
            }
            catch(erMs)
            {
                document.getElementById("idCurrentName").innerHTML = erMs;
            }
        };
        xhttp.open("GET", userUrl, true);
        xhttp.setRequestHeader('Content-Type', 'text/plain');
        xhttp.send();
    }
    catch(erMsg)
    {
        document.getElementById("idCurrentName").innerHTML = erMsg;
    }
}

请帮助访问 loclhost 上的数据。 谢谢!!

【问题讨论】:

  • 首先,检查您的浏览器控制台。您可能会在其中找到一条错误消息,指出此请求已被阻止,因为在响应中未设置 Access-Control-Allow-Origin 标头。如果是这种情况 - 然后阅读 CORS

标签: javascript spring-boot rest browser cors


【解决方案1】:

这个问题实际上与 CORS 有关。我最初添加了一个 chrome 浏览器扩展,但是当我在后端使用 SpringBoot 进行服务时,我在我的 RestController 上添加了注释 @CrossOrigin。这解决了 CORS 问题。

希望对你有帮助。

后端代码现在如下所示:

@CrossOrigin
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping(method = RequestMethod.GET, value = "")
    public User getUser() {
        return userService.getUser();
    }
}

【讨论】:

    猜你喜欢
    • 2015-03-19
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2019-09-05
    • 2014-08-10
    • 2012-03-28
    相关资源
    最近更新 更多