我有一个html页面的登录功能,不断返回我的错误400以上。 不管我输入什么。
我的html代码:
null
$(document).ready(function() {
$('#btnLogin').click(function() {
$.ajax({
url: '/api/User/LoginAsync',
method: 'POST',
contentType: 'application/json',
data: {
userName: $('#txtUsername').val(),
password: $('#txtPassword').val()
},
success: function(response) {
localStorage.setItem("accessToken", response);
window.location.href = "UserAccountPage.html";
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtUsername" placeholder="Username..." /><br />
<input type="text" id="txtPassword" placeholder="Password..." /><br />
<input type="button" id="btnLogin" value="Login" />
null
我的api
使用XML参数定义AJAX调用,但在API测试器中传递的是JSON格式
正确的AJAX调用必须是:
$(document).ready(function() {
$('#btnLogin').click(function() {
$.ajax({
url: '/api/User/LoginAsync',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({
userName: $('#txtUsername').val(),
password: $('#txtPassword').val()
}),
success: function(response) {
localStorage.setItem("accessToken", response);
window.location.href = "UserAccountPage.html";
}
});
});
});
contentType只涉及AJAX调用结果(它期望响应中有一个JSON)