Backbone.js Collection.fetch giving error - backbone.js

When I am trying to call the collections.fetch method i am getting the following error in console :
Uncaught TypeError: Object function (a){return new j(a)} has no method 'isObject'
Here is my app.js :
var Items = Backbone.Collection.extend({
url : function() {
return "names/all/" + this.pageStart + "-" + this.pageEnd;
},
pageStart : 1,
pageEnd : 5
});
var ScrollView = Backbone.View.extend({
el : $('#list'),
initialize : function() {
_.bindAll(this, 'getNames');
this.collection.bind('all', this.addAll);
this.collection.fetch(); //getting error coz of this line here.
},
getNames : function() {
this.collection.fetch();
},
addAll : function() {
alert(JSON.stringify(this.collection));
this.collection.each(function(item) {
alert(":");
this.addOne(item);
});
},
addOne : function(item) {
alert(item);
}
});
var coll = new Items();
var scrollView = new ScrollView({collection: coll});
Here is the scripts versions i am using
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
However the response i am getting from the server is OK 200 status
This is the respose i am getting
[{"firstName":"A","lastName":"last","id":"1"},{"firstName":"B","lastName":"last","id":"2"},{"firstName":"C","lastName":"last","id":"3"},{"firstName":"D","lastName":"last","id":"4"},{"firstName":"E","lastName":"last","id":"5"}]
And finally these are my response headers:
Request URL:http://localhost:8080/mongodb/names/all/1-5
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8080
Referer:http://localhost:8080/mongodb/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
X-Requested-With:XMLHttpRequest
Response Headersview source
Content-Type:application/json;charset=UTF-8
Date:Thu, 31 May 2012 17:32:10 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Please help someone.
Thanks in advance.

You use underscore 1.1.6 with backbone 0.9.2 which requires underscore 1.3.1.
See http://backbonejs.org/#upgrading
Upgrading to 0.9
If you're upgrading, make sure you also upgrade your version of
Underscore.js to the latest — 1.3.1 or greater.

Related

Angular $http.post 1.6.1 not passing data to WebAPI

All, I just created a new Angular package using 1.6.1 but now the data doesn't seem to pass to my WebAPI. However, when I post bits via SoapUI or something like that, everything is fine.
The Javascript looks like this:
function testapi()
{
var serviceRoot='http://server/testangular16/api/Values';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: 'PassInTheText'
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
};
function goodResponse(response)
{
console.log("Good response");
console.log(response);
}
function badResponse(response)
{
console.log("Bad response");
console.log(response);
}
and the webapi is a very simple C# controller:
// POST api/values
public HttpResponseMessage Post([FromBody]string value)
{
HttpResponseMessage rp = new HttpResponseMessage(HttpStatusCode.OK);
rp.Content = new StringContent(value);
return rp;
}
I am making it into the controller, I can set a break point and hit the parts where I can look at the value. It's always null.
Looking at the network trace, the angular part does do a preflight and I can see the 200 response back.
Request URL:http://server/testangular16/api/Values
Request Method:OPTIONS
Status Code:200 OK
Remote Address:10.7.14.209:80
**Response Headers view source**
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:content-type
Access-Control-Allow-Origin:http://localhost:8000
Cache-Control:no-cache
Content-Length:0
Date:Fri, 03 Feb 2017 18:09:04 GMT
Expires:-1
Pragma:no-cache
Server:"Management Corporation"
X-AspNet-Version:4.0.30319
**Request Headers view source**
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:mjvzrx3
Origin:http://localhost:8000
Referer:http://localhost:8000/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
So, it looks like I'm passing CORS, but when I get to trying to pass the data in as the content of the post, it doesn't make it.
Any ideas what I'm missing?
Thanks,
Nick
Web API expects an object in the message body, you cant pass in a primitive type unless you use application/x-www-form-urlencoded as the content-type and prefix the value with an equals = sign.
So you can fix it by one of these methods
Adjust the c# parameter and turning it into a type that has a string property and then send in a json object with a matching parameter name.
Change the request to url-encoding content type and add a = to the variable value.
Send it as a part of the URL instead of the message body, you can still use the POST method.
Change to form-urlencoded
function testapi()
{
var serviceRoot='http://server/testangular16/api/Values';
var deferred=$q.defer();
var req = {
method: 'POST',
url: serviceRoot,
data: '=PassInTheText', // added =
contentType: 'application/x-www-form-urlencoded' // specify content type
};
$http(req).then(goodResponse,badResponse);
return deferred.promise;
};
It seems if I do this, it works as expected.... Thoughts?
// POST api/values
public HttpResponseMessage Post(HttpRequestMessage request)
{
var data = request.Content.ReadAsStringAsync().Result;
Console.WriteLine("Data: {0}", data);
HttpResponseMessage rp = new HttpResponseMessage(HttpStatusCode.OK);
rp.Content = new StringContent("Data back from WebAPI" + data);
return rp;
}

Can't get this AngularJs HTTP request to work?

I'm trying to use the $http service in a angularJS app but I'm getting the below error in my console.
XMLHttpRequest cannot load http://example.com/data.service/getSomething/hghfg7igb757. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://other-example.dev' is therefore not allowed access.
This is my AngularJS Controller:
app.controller('mainController', ['$scope', '$http', function($scope, $http){
var url = 'http://example.com/data.service/getSomething/hghfg7igb757';
$http({
method: 'GET',
cache: true,
url: url,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).
success(function(status) {
//your code when success
$scope.data = data;
}).
error(function(status) {
//your code when fails
});
}]);
I've read this may have something to do with my server configuration, I'm using gulp-connect https://www.npmjs.com/package/gulp-connect. Or is it to do with the server config of the site I'm requesting from?
UPDATE
I checked the http headers with curl but it doesn't seem to tell me much?
$ curl -I http://example.com/data.service/getSomething/hghfg7igb757
HTTP/1.1 200 OK
Date: Wed, 07 Dec 2016 22:35:19 GMT
Server: WildFly/8
Expires: Wed, 07 Dec 2016 22:40:19 GMT
X-Powered-By: Undertow/1
X-dmg-elapsed-time: 30ms
X-dmg-host-address: 17?.??.???.?0
X-dmg-generated-time: Wed, 07 Dec 2016 22:35:19 GMT
Content-Type: application/json;charset=UTF-8
Content-Language: en-
X-dmg-node-name: dbfr_node_1
Vary: Accept-Encoding
X-Varnish-Bereq-Backend: real_backend_llr
X-Varnish-Bereq-Retries: 0
Last-Modified: Wed, 07 Dec 2016 22:35:19 GMT
Cache-Control: public, max-age=300
X-Varnish: 1376270
Age: 0
Via: 1.1 varnish-v4
X-Varnish-Cache: MISS
X-Varnish-Served-By-Host: jul.max.ie
X-Varnish-Served-By-IP: 1?.???.??.??
X-Varnish-Pool: http_pages
X-Varnish-Req-Backend-Hint: dead
X-Varnish-Req-Restarts: 0
X-Varnish-Hash: /data.service/getSomething/hghfg7igb757
X-Varnish-Backend-Ourself: varnish_server_jul_llr
X-DMG-Version: 6.20.51.2358
Accept-Ranges: none
Connection: keep-alive
How can I enable CORS with gulp-connect?
install cors package:
npm install --save-dev cors
then add it as middleware to connect:
var gulp = require('gulp');
var connect = require('gulp-connect');
var cors = require('cors');
gulp.task('connect', function() {
connect.server({
root: 'app',
middleware: function() {
return [cors()];
}
});
});
-- https://github.com/AveVlad/gulp-connect/issues/100#issuecomment-74369427
how can I check the headers in the response?
$http(...).
then(function onSuccess(response) {
// Handle success
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
}).
catch(function onError(response) {
// Handle error
var data = response.data;
var status = response.status;
var statusText = response.statusText;
var headers = response.headers;
var config = response.config;
...
console.log(headers());
});
$http's deprecated custom callback methods - success() and error() - have been removed. You can use the standard then()/catch() promise methods instead, but note that the method signatures and return values are different.
-- AngularJS Developer Guide - Migrating from 1.5 to 1.6 - $http
This turned out to be a CORs issue on the server side

S3 putObject fails using aws-sdk

It's driving me crazy, any help would be much appreciated!
To set up my bucket in S3 I followed http://www.cheynewallace.com/uploading-to-s3-with-angularjs/
Regarding this post I made following "improvements" by extended the policy with a wildcard and giving more rights
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:DeleteObject",
"s3:DeleteObjectVersion",
"s3:GetObject",
"s3:GetObjectAcl",
"s3:GetObjectTorrent",
"s3:GetObjectVersion",
"s3:GetObjectVersionAcl",
"s3:GetObjectVersionTorrent",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutObjectVersionAcl"
],
"Resource": [
"arn:aws:s3:::photos-eu/*"
]
}
]
}
and added < ExposeHeader>ETag< /ExposeHeader > to the Cors settings of the bucket
Then my angular service using the aws-sdk look like
/// <reference path="../../../typings/tsd.d.ts" />
module Services {
export interface IS3UploadService {
upload(imgName:string, imgData:string):ng.IPromise<{}>;
}
export class S3UploadService implements IS3UploadService {
static $inject = ['$q'];
private bucket:AWS.S3;
constructor(private $q:ng.IQService) {
var credentials = new AWS.Credentials("myAccessKeyId", "mySecretAccessKey");
AWS.config.update(credentials);
AWS.config.region = "eu-west-1";
this.bucket = new AWS.S3({params: {Bucket: 'peterparker-photos-eu', maxRetries: 10, region: "eu-west-1"}});
}
upload(imgName:string, imgData:string):ng.IPromise<{}> {
var deferred = this.$q.defer();
var params:AWS.s3.PutObjectRequest = {
Bucket: "peterparker-photos-eu",
Key: imgName,
Body: imgData,
ContentType: "image/jpeg",
ContentEncoding: "Base64"
};
this.bucket.putObject(params, (err:any, data:any) => {
if (err) {
console.error("->" + JSON.stringify(err));
deferred.reject(err);
} else {
console.info(data);
deferred.resolve(data);
}
});
return deferred.promise;
}
}
}
angular.module('App')
.service('S3UploadService', Services.S3UploadService);
For my test purpose, I push in the imgData an img encoded as Base64, something like "/9j/4AAQSkZJRgABAgAAZABkA...." (of course a valid image converted with http://base64-image.de)
And as result, each time I try, I've got following error
{"line":25,"column":24996,"sourceURL":"http://localhost:8100/lib/aws-sdk/dist/aws-sdk.min.js","message":"The request signature we calculated does not match the signature you provided. Check your key and signing method.","code":"SignatureDoesNotMatch","region":null,"time":"2016-06-08T15:12:09.945Z","requestId":null,"statusCode":403,"retryable":false,"retryDelay":60.59883770067245}
So much fun...
Update headers:
General
Request URL:https://peterparker-photos-eu.s3-eu-west-1.amazonaws.com/1465408512724.jpg
Request Method:PUT
Status Code:403 Forbidden
Remote Address:54.231.131.16:443
Response headers
Access-Control-Allow-Methods:HEAD, GET, PUT, POST, DELETE
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:ETag, x-amz-meta-custom-header
Connection:close
Content-Type:application/xml
Date:Wed, 08 Jun 2016 17:55:20 GMT
Server:AmazonS3
Transfer-Encoding:chunked
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request- Method
x-amz-id-...
x-amz-request-id:...
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de;q=0.2
Authorization:AWS ...
Connection:keep-alive
Content-Encoding:Base64
Content-Length:38780
Content-MD5:...
Content-Type:image/jpeg; charset=UTF-8
Host:peterparker-photos-eu.s3-eu-west-1.amazonaws.com
Origin:http://localhost:8100
Referer:http://localhost:8100/?ionicplatform=ios
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36
X-Amz-Date:Wed, 08 Jun 2016 17:55:20 GMT
X-Amz-User-Agent:aws-sdk-js/2.3.18
Request payload
Img base64 code
Update
Even by trying to upload a non Base64 content it finish with the same error
var paramsHtml:AWS.s3.PutObjectRequest = {
Bucket: "peterparker-photos-eu",
Key: "HelloWorld.html",
Body: "The Body",
ContentType: "text/html"
};
Update #2
I moved to a solution with a signed URL generated by my node js server as described in following solution, still got the same error as result...but I least I try ;)
upload file from angularjs directly to amazon s3 using signed url
Freak I finally find the solution or at least a solution.
After migrating my client aws-sdk based solution to a solution where the server generate a signedUrl I was still facing the same error. Short story long, it fixed the problem by setting in both side the Content-type for the header.
My code if someone face the same problem one day:
Server Node.js
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: "myKey", secretAccessKey: "mySecret"});
AWS.config.region = 'eu-west-1';
app.post('/api/images', securityPolicy.authorise, function (req, res) {
var s3 = new AWS.S3();
var imgName = req.body.imgName;
var contentType = req.body.contentType;
// Expires in seconds
var params = {Bucket: 'photos-eu', Key: imgName, Expires: 600, ContentType: contentType};
s3.getSignedUrl('putObject', params, function (err, url) {
if (err) {
res.status(500).json({
error: "Presigned S3 url for putObject can't be created. " + JSON.stringify(err)
});
} else {
res.json({url: url});
}
});
});
Client angular:
First or course there is the part to call the node server, obvious POST to my server
And then the second part processing the signedURL
private uploadToS3(preSignedUrl:string, imgData:string):ng.IPromise<{}> {
var deferred = this.$q.defer();
// Post image to S3
this.$http({
method: 'PUT',
url: preSignedUrl,
headers: {'Content-Type': 'image/jpeg'},
data: imgData
})
.then((response:any) => {
console.log("Image uploaded to S3" + JSON.stringify(response));
deferred.resolve();
}, (response:any) => {
console.log("Error Presigned URL" + JSON.stringify(response));
deferred.reject(response);
});
return deferred.promise;
}

spring RESTcontroller to accept dataURI

I am running into a issue of using angularjs ng-img-crop and Spring-boot REST web service.I want to upload an image file from ng crop to my backend web service.
I tried writing a spring controller but it failed and I couldnt find a good tutorial for this. help me resolve this basic request.
Thanks !!!
app.js
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'ngImgCrop'
])
.controller('Ctrl',['$scope','notify', function($scope,notify) {
$scope.myImage='';
$scope.myCroppedImage='';
var handleFileSelect=function(evt) {
var file=evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function (evt) {
$scope.$apply(function($scope){
$scope.myImage=evt.target.result;
});
};
reader.readAsDataURL(file);
};
angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
$scope.submit=function() {
notify($scope.myCroppedImage);
};
}]).
factory('notify',['$http', function($http) {
return function(myCroppedImage) {
var name = 'vishnu';
$http.post('http://localhost:8080/imageUpload', myCroppedImage)
.success(function(data, status, headers, config) {
alert("success");
})
.error(function(data, status, headers, config) {
alert("fail");
});
}
}])
controller.java
#RequestMapping(value="/imageUpload",method=RequestMethod.POST)
#ResponseBody
public String imageUpload(#RequestBody MultipartFile data){
return "success";
}
when I run with the following request, I got some exception in the web service.
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/imageUpload
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:application/json, text/plain, /
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:1850
Content-Type:application/json;charset=UTF-8
Host:localhost:8080
Origin:file://
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36**
Request payload
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAFIklEQVR4Xu3VsRHAMAzEsHj/pTOBXbB9pFchyLycz0eAwFXgsCF.......
Response header
Connection:close
Content-Type:application/json;charset=UTF-8
Date:Fri, 24 Apr 2015 12:40:35 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
Exception in java
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
First of all your controller should looks like:
public ResponseEntity<Response> fileUpload(#RequestParam("file") MultipartFile file) {
Use #RequestParam instead of #RequestBody, and send the file in a parameter with the same name you're using in the annotation.
Moreover, your request should be sent with type multipart/form-data. For example, a common html for would be:
<form method="POST" enctype="multipart/form-data" action="your url">

error fetching backbone model (works in chrome but not in firefox and ie9)

I have one service that returns proper data in chrome but ends in error for firefox and ie9. It looks like the GET returns 200 OK code, but still ends in error callback. I'm fetching data via backbonejs (with jquery.getJson and with ajax I'm getting the same result). The same result I'm getting also if I try to fetch data from remote server or locally.
Chrome: Version 23.0.1271.64 m
FF: 16.0.2
IE9: 9.0.8112.16421
wcf:
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/getData/{name}", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
List<Names> getData(string name);
serviceUrl:
"http://serverABC:4000/myService.svc/getData/test"
fetching from javascript:
via backbone or jqueryGetJson():
$.getJSON("http://serverABC:4000/myService.svc/getData/test", function () {
alert("success");
})
.success(function () { alert("second success"); })
.error(function (result) {
console.log('error:', result);
})
result:
"http://serverABC:4000/myService.svc/getData/test 200 OK 70ms"
headers:
Response Headers
Cache-Control private
Content-Length 6544
Content-Type application/json; charset=utf-8
Date Fri, 16 Nov 2012 14:09:46 GMT
Server Microsoft-IIS/7.5
Set-Cookie ASP.NET_SessionId=s3aguluzip0dw135glbxlwwf; path=/; HttpOnly
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Host svgwbip93:4000
Origin http://localhost:51280
Referer http://localhost:51280/Default.aspx?ReturnUrl=%2f
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0
result from debug:
readyState 0
responseText ""
status 0
**statusText "error"**
abort function()
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function()
overrideMimeType function()
pipe function()
progress function()
promise function()
setRequestHeader function()
state function()
statusCode function()
success function()
then function()
toString function()
Response: - is empty (this is most probably the problem (but as I mentioned in Chrome I'm getting correct json data)
EDIT 1:
I tried to get raw response with fiddler and I'm getting the JSON. The big question is that why callback falls to error.
Here is my raw response:
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 29
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=kuv3g0r2dgmu5bpaoayj5lic; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 16 Nov 2012 19:32:58 GMT
{"PlatformDrawingsResult":[]}
I verified the json - it seems OK, so what can be the problem....hmm. I forgot to mention that I'm using also requirejs (not sure if that will bring some light,..)
Cheers, Miro
The solution is (thanks to jwkeenan) :
I put this line at the beggining of each method in my web service and
now all browsers work.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
and to get it to work in ie9 I needed to add this to my web app:
$.support.cors = true;

Resources