backbone restful api server return - javascript

I have been trying to look for more information about the restful api, I have found many places talk about what request (method and data) to make for retrieve, create, update object in server, but I couldn't find a place that explains what the server side should return. specifically for backbone.js.
I understand for GET method to a "path/:id", the server would probabily return an stringify json object "{id:1,data:aaa}", or an array of json object. but for create, update and delete, I don't know what the server should return so backbone will acknowledge that server has successfully created the object? I found some api does this:
create successful returns:
{ "createAt":"2014-1-01 11:59pm"}
or failed returns
{ "error":true}
some api does this:
{"sucess":true}
or
{"error":true}
What is the result that backbone expect?
Thanks

Backbone generally expects the following:
Create should return a JSON representation of the object
including an id property with a 201 status (Created).
Read should return a JSON representation of the object including
an id property with a 200 status (OK).
Update should return a 204 status on success (No content).
Destroy should return a 200 status on success (OK).

Related

Fetch GET request unhandled rejection

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).

Insert data in response of Message class in c#

I need to insert in a response information in the body of this with c#.
Currently I have a function that inserts a custom message in an HttpResponseMessageProperty object which is validated from the web client observing response.statusText.
When accessing from https we discover that this data is not being sent since the requests are being made from http \ 2.
Instead of how we are sending it, I would like to know in what way I could send that data through the body.
The following code works with http 1.1. And response is of class Message
if (message.Length > 0) {
property.StatusDescription = message
}
response.Properties[HttpResponseMessageProperty.Name] = property;
Later that Message object is returned through RequestContext Reply.
How can I include data that I can later read from response.data in javascript?
Thank you all
EDIT:
I'm using Net Framework 3.5

How to send data in request body with a GET when using jQuery $.ajax()

The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}

After creating new instance in collection, don't do a GET request on the endpoint (backbone)

After I add a model instance to a collection, I do a POST request to add it. Then a GET request is done to get the model from the server. Is there a way to not to the GET request, only the POST request? Also, is it possible to get the success and error callback functions to respond to the success and failure of the POST request?
I want to do this because the collection has a URL that parses the JSON data that gets back, so the GET request doesn't work, but the POST request does work. I don't want to do a GET request on a endpoint that doesn't work.
The GET request is unnecessary. On the server in your POST handler you should return a JSON result back to the client representing the model. This is especially useful when there are generated fields such as an id. Then on the client in the success callback you can grab the model returned from the POST.
In the following example a new model is added to the collection if successful. I've also included the error callback which will fire if either client side validation fails or the POST fails:
var isNew = this.model.isNew();
this.model.save({}, {
success: function(model, response) {
if (isNew && this.collection) {
this.collection.add(model);
}
},
error: function(model, response) {
var errorMsg;
// Response may be string (if failed client side validation or an AJAX response (if failed server side)
if (_.isString(response))
errorMsg = response;
else
errorMsg = response.responseText;
}
});
The process you follow is indeed unnecessary. You should be using create on the collection to directly add the model, and invoke sync (the POST in this case) in the same time.
For example:
collection.create({foo: 'bar'}); or collection.create(unsaved_model);
The result of invoking create will return either the (saved) model or false if this was not successful. In addition it is possible to wait for the model to be saved before adding to the collection by doing
collection.create({foo: 'bar'}, {wait: true});
The documentation is your friend.

In Backbone.js, after I perform a collection.fetch({'add':true}), how do I get the latest elements retrieved?

I called fetch, and it hits the server.
Now...my server returns models back...how can I get those just-added models?
the fetch method has a success callback with the following signature:
success: function(collection, response){
}
the collection argument is your collection with the newly added models as well as whatever was there previously. response is the json response from the server. So you could look up the models in collection using the ids from response to get the 'just-added models'.

Categories

Resources