【发布时间】:2019-07-10 17:16:53
【问题描述】:
我是 Spring 和 AngularJS 的新手,我正在尝试创建从后端到前端控制器的路由。 我的 Spring 后端:
@Controller
@RequestMapping("test1")
public class TestController {
public TestController() {}
@RequestMapping(value="test2", method=RequestMethod.GET, produces= MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
@Transactional("defaultTransactionManager")
public String getSearch() {
System.out.println("It reaches here!");
return ("Test Success!");
}
}
我的 AngularJS 前端:
this.testingHTTP = (vm) => {
$http({
method: 'GET',
url:SERVICE_URL + '/test1/test2',
headers: {
'Content-Type': 'application/json'
},
}).then(function successCallback(response) {
vm.testerDiv = response;
}, function errorCallback(response) {
console.log(response, 'Test failed');
});
};
当我运行前端函数时,“它到达这里!”出现在我的后端控制台中,这出现在我的浏览器控制台中:
TypeError:无法读取未定义的属性“消息” 在 handleResponseError (defaultServices.js:48) 在 processQueue (angular.js:17330) 在 angular.js:17378 在 Scope.$digest (angular.js:18515) 在 Scope.$apply (angular.js:18903) 完成后(angular.js:12775) 在 completeRequest (angular.js:13032) 在 XMLHttpRequest.requestLoaded (angular.js:12937) “测试失败”
我知道网址是正确的;可能是关于我的 Content-Type 吗?我错过了什么?
【问题讨论】:
-
在函数successCallback之后添加
console.log(response);,然后在控制台看到真正得到的结果。也许this.testerDiv = response;会导致错误 -
还有一些给你的建议:1-) 使用 Angular 2 或更高版本 2-) 使用 nice word 清洁代码(什么是 test1,test2 用于请求映射) 3-) 学习注释并在何时使用你只需要(@ResponseBody @Transactional("defaultTransactionManager") 用于测试你不需要)
-
它失败了。在浏览器控制台输出中,您可以看到它显示“测试失败”。但是,我将内容类型切换为“文本/纯文本”,成功回调已激活,但响应未定义,而不是“测试成功!”应该是这样。
-
1) 不能使用角度;公司使用 angularjs 2)test1 和 test2 是 stackoverflow 的路由 3)我不熟悉 Spring,我正在从项目的另一部分复制代码。我没有意识到它与调试无关
-
如果要返回 json,请尝试将返回值包装在 DTO 类中。该字符串无法转换为有效的 json。由于没有返回有效的json,所以angular无法解析成
response对象。
标签: javascript java angularjs spring spring-mvc