I have a simple Backbone.js/Bootstrap front end in HTML5 with a Node.js/Restify backend. I am setting cookies in a header response from the server as below:
res.setHeader("Set-Cookie", ["token=ninja", "language=javascript"]);
On the client side, I am making a REST call as
var response = this.model.fetch().success(function(data){
//success
}).error(function(data){
//error
}).complete(function(data){
//complete
});
that callsback a parse method in the model.
How can I read the cookie value in the model?
Include Cookie.js.
You can then reference individual cookies like this:
var token = Cookie.get('token')
# token == 'ninja'
Here is what I figured out. My application has two components - the HTML/js from one domain that talks to a REST sevice on another domain (and therefore is cross-domain.) Because the cookie is set from REST, it appears is not readable across domains. So the web page will not store the cookie even though the server is sending it. One alternative is to use local cookies or use the technique illustrated by http://backbonetutorials.com/cross-domain-sessions/.
Assuming you are using jQuery with Backbone, you can get the headers by defining the parse function in your model by calling getAllResponseHeaders or getResponseHeader:
var model = Backbone.Model.extend({
// the rest of your model
parse: function(resp, xhr) {
var allHeaders = xhr. getAllResponseHeaders();
var cookieHeader = xhr. getResponseHeader("Set-Cookie");
// do something with the headers
return resp;
}
});
Related
I'm using Ember-Data 1.0.0.Beta-9 and Ember 1.7 to consume a REST API via DreamFactory's REST Platform. (http://www.dreamfactory.com).
I've had to extend the RESTAdapter in order to use DF and I've been able to implement GET and POST requests with no problems. I am now trying to implement model.save() (PUT) requests and am having a serious hiccup.
Calling model.save() sends the PUT request with the correct data to my API endpoint and I get a 200 OK response with a JSON response of { "id": "1" } which is what is supposed to happen. However when I try to access the updated record all of the properties are empty except for ID and the record on the server is not updated. I can take the same JSON string passed in the request, paste it into the DreamFactory Swagger API Docs and it works no problem - response is good and the record is updated on the DB.
I've created a JSBin to show all of the code at http://emberjs.jsbin.com/nagoga/1/edit
Unfortunately I can't have a live example as the servers in question are locked down to only accept requests from our company's public IP range.
DreamFactory provides a live demo of the API in question at
https://dsp-sandman1.cloud.dreamfactory.com/swagger/#!/db/replaceRecordsByIds
OK in the end I discovered that you can customize the DreamFactory response by adding a ?fields=* param to the end of the PUT request. I monkey-patched that into my updateRecord method using the following:
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
// hack to make DSP send back the full object
adapter.ajax(adapter.buildURL(type.typeKey) + '?fields=*', "PUT", { data: data }).then(function(json){
// if the request is a success we'll return the same data we passed in
resolve(json);
}, function(reason){
reject(reason.responseJSON);
});
});
}
And poof we haz updates!
DreamFactory has support for tacking several params onto the end of the requests to fully customize the response - at some point I will look to implement this correctly but for the time being I can move forward with my project. Yay!
EmberData is interpreting the response from the server as an empty object with an id of "1" an no other properties in it. You need to return the entire new object back from the server with the changes reflected.
I am uploading a file to the server using BackgroundTransferRequest object. I need to access the response header sent from the server. Based on the research, I understand that there is no direct access to the Response of the request and one possible work around is to provide a download location to which the response content will be written.
However, when I try to do that, there is no data written to that file and its 0 bytes. My request server is actually sending a response having ONLY the headers (without any content).
So my question is, does the response have to have body in order to get the response written to the DownloadLocation?
My code sample:
var request = new BackgroundTransferRequest(targetUri)
{
DownloadLocation = new Uri(downloadTo, UriKind.Relative),
UploadLocation = new Uri(uploadFrom, UriKind.Relative),
Method = "POST"
};
I understand that when I submit a form, according to the documentation ExtJs by default parses the response as JSON.
In my case, the server returns HTML, that I want to display in a Panel. When I submit the from using getForm().submit(), ExtJs will throw an error about invalid JSON:
Ext.JSON.decode(): You're trying to decode an invalid JSON String
How can I tell ExtJs not to attempt to parse the response ? I could the access the text with the response object.
I don't know if you are looking for strictly an ExtJS framework solution. However, it seems you may be able to solve your issue possibly using xmlhttprequest directly since you are looking to push the html returned directly to dom?
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET','/myPath/here',false);
xmlhttp.send();
var html = xmlhttp.responseText;
//assign value
In Ext.form.Basic configuration you can define your own reader and errorReader
Finally, it was impossible for me to get to work the form.submit() of ExtJs. I needed an implementation using Ext. And since this is a frequent pattern in my application, it is important to have a short an simple solution.
This is what I finally found (I have a modal window containing the form):
var values = me.up('form').getValues(),
panel = Ext.create('My.view.MyPanel', {
xtype: 'panel',
loader: {
url: Paths.ajax + 'sav_vpc/douane.php',
method: 'get',
params: values,
autoLoad: true
}
});
me.up('window').close()
This solution has another advantage over the me.up('form').getForm().submit() solution:
While .getForm().submit() is asynchronous, .getValues() is synchronous. Therefore, it is possible to close the window immediately.
I got a Web API that performs a function and posts a JSON response back to a calling page.
This is standard Web API behaviour and works beautifully.
Now I want to modify the controller so that in addition to the post back the user is redirected back to the page on the calling web site where the result of the Web API call can be displayed (in JSON).
So basically I want to:
(1) Server side post back the results in JSON to a page and redirect to the same page from the Web API
(2) On the caller's site, I want to display the JSON that was posted back.
How do I do this?
I already tried for many hours ...
e.g.:
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "text/json");
client.Headers.Add("Accept", "text/json");
try
{
ErrorText = client.UploadString(redirectURL, "POST", JsonConvert.SerializeObject(orderresponse));
Response.Redirect(redirectURL);
}
catch (WebException err)
{
ErrorText = err.Message; //Todo - write to logfile
}
}
Instead of doing the redirect on the server, instruct the client to do it by using the appropriate HTTP status code. For example:
public HttpResponseMessage Post(MyModel model)
{
// handle the post
MyResult result = ...;
// redirect
var response = Request.CreateResponse<MyResult>(HttpStatusCode.Moved, result);
response.Headers.Location = new Uri("http://www.yourdomain.com/redirectURI");
return response;
}
I am relatively new to NodeJS, but I'm porting an existing API server written in PHP to use NodeJS. I started out looking at Express, but realised that with all the layout-rendering and templating stuff in Express, it wasn't suited for the task. Then I looked at Restify, but realised it's REST-ness wouldn't work with the model of this API.
I don't want anything that is tied to a database, or any specific way of setting out the API endpoints. Is the best solution to fully roll my own server, without the help of any libraries?
EDIT: Sorry, it seems I was unclear. I am trying to recreate the PHP API as close as possible, and the PHP version does not use REST. It has a few different PHP scripts which take some POST parameters.
If you just want a simple JSON API, Express is still an option. Layouts, temptating and middleware are optional, and you can just use simpler functions.
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(req, res) {
// req.body is an object with POST parameters
// respond with JSON
res.json(200, { data: 'payload' })
// or show an error
res.json(500, { error: 'message' });
});
app.listen(80);
That is one of the simplest solutions available. Unless you want to do request body parsing, checking the HTTP request method, other things yourself, then you can create your own server. That would look more like this:
var http = require('http');
http.createServer(function(request, response) {
if (request.method === 'POST') {
var data = '';
request.on('data', function(chunk) {
data += chunk;
});
request.on('end', function() {
// parse the data
});
}
}).listen(80);
A method like so would also require checking the path as well as other things that would be handled automatically in Express.