首页 > 解决方案 > 进行 javaScript 调用以使用在 localhost 上运行的 REST API

问题描述

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

@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 上的数据。谢谢!!

标签: javascriptspring-bootrestbrowsercors

解决方案


这个问题实际上与 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();
    }
}

推荐阅读