I have a resource to retrieve from endpoint. Passing filters to retrieve the resource is making URL to be long so I am having to pass filters in body . So I am using POST for retrieving a resource is it agains the REST standard ? Also shall I use status code 201 for POST or 200 for POST success is also fine ?Also in reponse body shall I pass message description or is there any standard for message description and error codes json.
200 should be the successful response header. If you respond with a json you could/should use a key named success to indicate if the operation was successful or not. The actual response data stays usually under the data key. If the success is false there should be and error code under the code key and a error message under msg key.
I don't say these above are STANDARD but they are a often used convention.
{
success: true.
data:[1,2,3],
total: 3
}
{
success: false,
code: 101,
msg: "Division by zero.'
}
Related
I'm doing a basic request to a backend in JS (only to check a user instance exists and will return a bool (true/false) to prevent returning full user data until needed)
From what I have been told by peers it's ill-advised to be passing sensitive data (in this case people's emails) via paths and should be via the body (I haven't looked into why) Anyway, so the way I configured it was to be contained within the body like this:
GET http://localhost:8080/User/check
Content-Type: application/json
{
"email" : "B.Nye#ABC.uk"
}
However when doing this call in JS:
if (isAuthenticated){
console.log("test -----------")
console.log(user.email)
fetch("http://###.###.###.###:8080/User/check", {
method: "GET",
headers:{"Content-Type":"application/json"},
body: JSON.stringify( {
email: "B.Nye#ABC.uk"
})
}).then((result)=> {
if (result.ok){
console.log("sucess")
}
else{
console.log("fail")
}})}
I get this error:
Unhandled Rejection (TypeError): Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
Is there a way to bypass this or am I restricted to using either a POST method and reworking my backend method or containing the users email inside of the path?
Firstly if you want to use body, you should use POST method. This is why the Fetch API keeps sending errors to you.
The second question is, why do we not use GET method while we are sending sensitive datas like emails, passwords etc. The answer is, entire URL is cached user's browser history and it may expose user's sensitive data. And it will be much more secure if you use POST method because it prevents data leakage via the query string (you are sending data in the body).
I'm working on simple Chatbot in Line Messenger. I found some API which I want to use in the following way:
User sends specific key word like !send data. Then I send HTTP Request using request module. I'm getting the response and I output it in the console just to see if everything is correct. I'm parsing the repsonse with JSON.parse(body) and I'm able to access its specific values with
result = JSON.parse(body);
console.log(result.value.text);
Now I want to send result.value.text as a reply mesaage to the Line client.
Message has form
message = {
type: "text",
text: "someString"
}
But how can I pass the part of HTTP response to this object? Trying something like this
LINEResponse = {
type: "text",
text: result.value.text
};
leads to
UnhandledPromiseRejectionWarning: Error: Request failed with status code 400
I'm not 100% sure if its even correct approach implement this. I would appreciate any help
I am trying to build a simple check that will accept a string and check to see if a twitter account exists by that string.
I have successfully managed to get a positive result, but I can't seem to get a negative one. $.ajax() has an error element, but it is not firing.
Working Example
Code:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(){
alert("username is valid");
},
error: function(){
alert("username is valid");
}
})
}
You are using the JSONP transport. In this transport, the requested URL is simply added as a <script> tag in the document. If the URL returns a non-200 status code, the browser won't execute it: that's why you can't see negative responses.
One solution is to use the suppress_response_codes parameter, so that the API always return a 200 status code.
See Things Every Twitter Developer Should Know:
suppress_response_codes: If this parameter is present, all responses will be returned with a 200 OK status code - even errors. This parameter exists to accommodate Flash and JavaScript applications running in browsers that intercept all non-200 responses. If used, it’s then the job of the client to determine error states by parsing the response body. Use with caution, as those error messages may change.
BTW, Twitter is suppressing non-authenticated access to the API, so JSONP access may be suppressed too.
Just a summarize of arnaud576875's answer:
Add a suppress_response_codes=1 parameter
Check for ID returned
So, the result will be something like this:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?suppress_response_codes=1&screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(d){
if (d && d.id)
$('span').html('username is valid!');
else
$('span').html('username is not valid.');
}
});
}
Usually API's always returns a response when a request is received. That's why no error is given. You should parse the response coming from the API to find out if a user exists or not.
Errors are not triggered when using JSONP-requests. Read more at jQuery Forums.
I am persisting the data in a textbox before redirecting the page to another. When the user clicks the back button in the page load function of the page (in javascript) I am getting the data from the textbox like
var pageval = $('#grid')
.load('/Dealer/AllClaims?page=5&__=634673230919806673 #grid', CallBackFunction);
I want to send an AJAX call by using the URL from the above data. I.e from /Dealer/AllClaims?page=5&__=634673230919806673 #grid. So I replaced the 'pageval' unnecessary data with (.replace()) in javascript. Now I store it as
var urlmain = '/Dealer/AllClaims?page=5&__=634673230919806673 #grid';
When I send an AJAX call with this 'urlmain' like
$.ajax({
type: "GET",
url: urlmain,
success: function (data) {
$("#allclaimsdiv").html(data);
},
it throws error like 'status not found' as the URL is like
http://localhost:46408/Dealer/%22Dealer/GetDealerClaims?page=3&__=634673387913756213
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
The above bold data is there in the URL before users click on the back button. I think it is concatenating the data.
But for testing purpose I had given directly the URL as:
$.ajax({
type: "GET",
url: "/Dealer/AllClaims?page=5&__=634673230919806673 #grid",
success: function (data) {
$("#allclaimsdiv").html(data);
},
Then it works fine.
What is the difference between these two? Why doesn't it work?
you have a problem in the called url:
first: there is a /22 which stands for a url-encoded doublequote
second: you have Dealer two times in the url - so you may have to remove /Dealer from your urlmain
Is there a quote character getting encoded somewhere along the line? The reason I'm wondering is the URL you've given in bold has "%22" in it:
http://localhost:46408/Dealer/%22Dealer/
See here for some info on what certain characters get encoded to.
A 500 error means a problem has occurred on your web server. Check your server log files or enable error reporting for more info - that might give you some hints or even tell you exactly what's wrong.
In jQuery, I'm submitting forms to the server. When there is a validation error, I receive a 400 error from the server, and the body of the document is valid JSON. I would like to know how to access the data returned from the server.
My .error callback function on the jQuery.Ajax object is never called, so I'm using .statusCode{400} function. This runs just fine, however none of the arguments contain the response body.
I try to get json response with a status 400, and it works on IE7,8 and 9, Firefox and Chrome (Safari not tested).
...
error: function(xhr) {
error(xhr.responseText);
}
...
Some browsers' XHR implementations refuse to provide the response body if the HTTP status is not 2xx. What I've had to resort to in API design where I couldn't control my clients was to do something like always return 200 and indicate success/failure/status in some other way (e.g., as a top-level attribute in the JSON response).
I have had no trouble using statusCode in the callback, However, statusCode as a callback function Does NOT return any data.
jQuery.Ajax
I think you should try a different approach on how to handle validation errors in the server side, to return status code 200, but with a parameter like "error_count" and go from there.
can you post some of the code you are using (just $.ajax you are using...) ?
For me (Chrome), responseText property of the xhr response contains only "BAD REQUEST" when statusCode is 400. Thanks Steven for your response; I was struggling with this since in Postman I could get the json data I was returning from my REST controller, but couldn't find it on the jQuery Ajax response.
"If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object."
http://api.jquery.com/jquery.ajax/
If you're specifying your callback with statusCode as mentioned in the question:
"If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback." (jqXHR, textStatus, errorThrown)