javascript - 进行 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 上的数据。谢谢!!
解决方案
这个问题实际上与 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();
}
}
推荐阅读
- node.js - 如何在 JOI 验证中自定义消息
- git - Git如何撤消最近的合并提交然后更改为变基
- php - 如何对所有元素值求和并将该数字附加到数组的末尾?
- angular-material - 如何从角度材料转换日期格式
- java - 移动迭代器语句使代码编译
- javascript - 如何在这个 Chrome 扩展代码中有多个指令?
- prolog - 从列表 Prolog 中挑选元素
- swift - 为什么 serviceSubscriberCellularProviders 返回 nil?(在 iOS 12 中)
- python-3.x - TypeError:需要一个整数(得到类型 str)?
- c# - 获取每个 URL 目录