React js AJAX sends sometimes GET instead of POST and getting 304 strange - ajax

I've got a problem and I have no idea why it appears. The circumstances of its appearance are very strange for me...
I've got a POST REST service /login. It expects json {"email":email,"password":password}. I am using ajax and everything works correctly... except for the case when email (is in real format) contains '#' sign and some letters before and after( I know it is strange but only in this case such error appears). When I pass email i.e "mum#mum.com" then few things are happening:
I see that browser sends GET request instead of POST and obtains 304 http status
In the browser console I see infomation "The development server has disconnected. Refresh the page if necessary" and page refreshes automatically
The above things happen only when email is in format I described above.When I pass "aaa" or "aaa#" as email everything works correctly(browser sends POST request and I don't get error in console).
I honestly have no idea why this happens... would be extremely grateful for your help and I will answer all your questions concerning this.
PS.
When I use REST web service tool in IntellJ everything always works fine.
handleLogin() {
const input = {
email: this.state.email,
password: this.state.password
};
$.ajax({
url: CONST.USER_SERVICE + "/login",
type: "POST",
data: JSON.stringify(input),
contentType: "jsonp"
})
.fail(function () {
alert("Wrong data");
})
.always(function (arg1, arg2, arg3) {
if (arg3.status === 200) {
alert("ok!");
}
}.bind(this));
}

Try making the ajax request like data: input without stringify. Ajax expects an object.

Related

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

A 405 status code from web API after trying to send PUT data in body

ok.
I'm using Web API to make AJAX requests.
I'm trying to send a PUT request to an action on a controller.
I'm using route attributes.
When I'm sending the data as part of the route data, everything is fine and the action gets the right info.
However, when I'm trying to send the data in the body, I get a 405 status ((Method is not allowed).
I'm also adding the [FromBody] attribute to the parameter. Here's by jQuery call:
type: 'PUT',
url: 'api/ServerQueue/activity',
data: "=2",
success: function (xhr) {
$("#load").hide();
},
error: function () {
$("#load").hide();
}
};
Here's my action:
[Route("status/{status}")]
public string PutStatus([FromBody]int status)
{
}
I placed a "RoutePrefix" on the controller body.
BTW, I'm using VS 2012.
Any idea what could be the source of the problem?
Try changing the route configuration from
[Route("status/{status}")]
to
[Route("status")]

Using ajax to GET a token from external site returns empty response

I have two sites right now. One that has a token and one that is supposed to allow a user to do stuff with the token.
When I visit the first site that has the token, mySite.local/services/session/token it shows it: OTV4Gu9VQfjIo2ioQ0thajdEJ6nEINoxsLuwgT_6S0w
When I am on the page that is supposed to GET this token, I get an empty response and the error for the ajax function is thrown.
The weird part is that when investigating the issue with firebug, I can see the response for the ajax request is 43B - the same size as the token. So for some reason the page with the token is being hit properly, but the response is not coming through.
Here is a screenshot of the firebug response:
And here is the JQuery with the ajax request:
var nid; //global node id variable
$('html').click(function(){
try {
$.ajax({
url:"http://mySite.local/services/session/token",
type:"get",
dataType:"text",
error:function (jqXHR, textStatus, errorThrown) {
alert('error thrown - ' + errorThrown);
console.log(JSON.stringify(jqXHR));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (token) {
//Do some stuff now that token is received
}
});
}
catch (error) {
alert("page_dashboard - " + error);
}
});
Your running into the Same Origin Policy which essentially states any request done by client side/browser language like Javascript must be on the same port, with the same domain name and the same protocol. In your case http://mysitemobile.local does not equal http://mysite.local so you're request is being blocked. Firebug's way of displaying that is no response with 43 bytes.
There are two ways to work around this, Cross-origin resource sharing (CORS) or JSONP. CORS is a HTTP header that is added to the server you are requesting to and provides a whitelist of acceptable domains that are allowed break the same origin policy. Most recent browsers support this header.
The other option is JSONP, wraps a JSON object into a Javascript function that is called using <script> tags normally. If the other server returns {status: 0} and you have a function called parseStatus() in your code that the remote server would wrap into parseStatus({status:0}); thus calling your function without having to worry about the same origin policy.

How to debug the ajax request in django

I know that for example:
def home(request):
if request.method == 'POST':
k = 'p' % 1
return HttpResponse(simplejson.dumps(dict()), mimetype='application/javascript')
else:
k = 'p' % 1
return render_to_response('index.html',locals());
url(r'^$', 'app.home'),
If I use the browser to visit the home page, django will return a debug page to me and show that there is an error in k = 'p' % 1
But if I use the $.ajax() to send a post to this view, the console of chrome only show POST http://(some url here):8000/ 500 (INTERNAL SERVER ERROR)
so is there any good way to debug the second case?
I have no idea about debug the django, is there anybody have better way to debug the django?
thanks
have a look at sentry (and the corresponding raven)
(the Network tab should be able to show you the request and the corresponding response. i believe newer django versions even give you a more bare-bones version of the stacktrace if the request was ajax)
There is an error CallBack in ajax. It will spew out the actual error.
$.ajax({
type: 'POST',
url: '{% url 'url_name_for_your_view_here' %}',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
dataType: "text",
success: function(response) {
//do something here if everything goes well
},
error: function(rs, e) {
alert(rs.responseText); //throw actual error, just for debugging purpose
alert('Oops! something went worng..'); // alert user that something goes wrong
}
});
There are a number of third party apps make debugging ajax easier. I've used this in the past with success: https://github.com/yaniv-aknin/django-ajaxerrors
Or if you prefer not use an app, chrome developer tools will likely be enough, as is suggested in this thread: Django: Are there any tools/tricks to use on debugging AJAX response?

ajax json request , always returning error

Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.

Resources