问题描述:
1. 想在JSP页面测试调用后台接口,这个接口调用后需要进行页面跳转,所有无法使用Postman等工具
2. 接口接收的是JSON数据格式
代码展示:
<html>
<head>
<title>接口测试</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
function login() {
var myData = {
"account": "danisa",
"password": "111111",
"userType": 1
};
$.ajax({
type: "POST",
url: "http://127.0.0.1:8088/api/1.0/web/login",
data: JSON.stringify(myData),
contentType: "application/json;charset=UTF-8"
});
}
</script>
<h1>登录</h1>
<input type="button" value="click me to login" onclick="login()">
</body>
</html>
其中需要注意的有两个地方:
1. contentType,需要填成 application/json;charset=UTF-8,否则会报格式错误
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
2. data部分,要使用JSON.stringify()方法格式化json对象,否则会报以下错误
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'account': was expecting ('true', 'false' or 'null')