c# - Cannot load web api method using Backbone.js -
i have blank asp.net solution 5 different projects. 1 of them asp.net web api , other 1 blank web site bunch of html pages. using backbone.js/jquery make calls web api within solution. blank web site running on different port , web api running on different port.
//collection var auditscollection = backbone.collection.extend({ url: 'http://localhost:56501/api/searchaudits', sync: function (method, model, options) { if (!options.crossdomain) { options.crossdomain = true; } options.timeout = 1000; alert(method + ": " + json.stringify(model)); return backbone.sync(method, model, options); }, }); var audits = new auditscollection(); // model var audit = backbone.model.extend({ }); var audit = new audit({ auditnumber: "a12" }); audits.add(audit);
// post call - sending model , expecting json object in response.
audit.save({}, { success: function (response) { alert("got audits successfully" + response); }, error: function (response) { alert("error.. go home now"); } });
i still error
xmlhttprequest cannot load http://mydomain:56501/api/searchaudits
. request header field content-type not allowed access-control-allow-headers.
i think figured out issue is. project setup in following structure.
error:
-- solution
-- project 1 (web api) - running on `http://localhost:80/api` -- project 2 -- project 3 -- project 4 (views) - running on `http://localhost:3000/`
so when started making ajax requests, started giving exceptions like
xmlhttprequest cannot load http://localhost:80/api/searchaudits
. request header field content-type not allowed access-control-allow-headers.
options localhost:80/api/searchaudits
405 (method not allowed)
xmlhttprequest cannot load /api/searchaudits
i did not know going consider domains different ports ad different domains.
solution:
override backbone.sync method - reference
in web api projects web.config file, add following
<system.webserver> <httpprotocol> <customheaders> <add name="access-control-allow-origin" value="*" /> <add name="access-control-allow-headers" value="origin, x-requested-with, content-type, accept"/> </customheaders> </httpprotocol> </system.webserver>
there answers in stackoverflow regarding issue in bits , pieces, effort put complete solution in 1 place.
Comments
Post a Comment