I am making a post request from the client to the API endpoint. On successful login, API returns a JWT token.
The API perfectly works when sending the request on Postman as illustrated on the picture below:
However, when I try to make this request from the client, using AJAX request in order to save the JWT in the local storage on the client, the request does not even appear in the log. So, I assume that something is wrong with my AJAX call.
Here is the client code:
<script type="text/javascript">
$('#button1').click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: {email: "test1@reg.ru", password: "123"},
contentType: "application/x-www-form-urlencoded",
url: 'http://localhost:3000/api/login',
success : function(data){
localStorage.setItem('token', data.token);
alert('ok');
},
error: function(result) {
alert('error');
}
});
});
</script>
<button id="button1">Test API login</button>
What am I doing wrong?
The selector isn't correct. Change $('button1').click
to $('#button1').click
尝试在ajax请求中添加dataType: json
属性,可能返回值的模式不正确,因此将执行错误回调。
@charlietfl correctly pointed out "the button doesn't exist when the javascript runs".
So, when I changed the code to:
<script type="text/javascript">
$(document).ready(function() {
$('#button1').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: {
email: $('#inputEmail').val(),
password: $('#inputPassword').val()
},
url: 'http://localhost:3000/api/login',
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
});
});
</script>
It started to work.
Thanks everybody for trying to help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.