Ember.js 2 Calls to .net API - c#

I am building a SPA ember.js app that will hit a .net API via an ajax call.
ember.js
getData: function(){
$.ajax({
type: "POST",
url: "http://localhost:9001/controller",
dataType : "json",
headers: "Access-Control-Allow-Origin",
contentType: 'application/json; charset=utf-8',
success : function(data) {
return data;
},
error:function(data){
alert('test' + data);
}
})
}
It returns an error message : SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () { return _emberRuntimeSystemString.fmt(this, arguments); }' is not a valid HTTP header field value.
I have been hammering away at this issue for a few hours now and I just can't seem to get around it. Also very new to ember.js.
If anyone has a better idea of whats going on...

Well,
the problem is in your headers. You are not giving "Access-Control-Allow-Origin" a value.
So you want something like
headers: {"Access-Control-Allow-Origin": 'value' }
Also, I don't think that particular header is used that way? I believe it's a header that the server sends.
Check this post out - How does Access-Control-Allow-Origin header work?
Pav

Related

JQuery Cross Domain Error - No 'Access-Control-Allow-Origin'

The POST request
var url = "http://xxx.xxx.x.x/MyServices.svc/GetOrders";
$.ajax({
type: "POST",
url: url,
crossDomain : true,
data: 'abcd',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
data = result.data;
},
error: function (xhr, ajaxOptions, thrownError) {
debugger;
alert('error');
}
});
When the url address is localhost i am getting a response
When trying to do so across servers I am getting an Error:
405 (Method Not Allowed)
XMLHttpRequest cannot load http://xxx.xxx.x.x/MyServices.svc/GetOrders. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
All of the answers on the web where inconclusive.
If you can deal with json in return, then try using jsonp for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ....
As documented in official site :-
The advent of JSONP — essentially a consensual cross-site scripting
hack — has opened the door to powerful mashups of content. Many
prominent sites provide JSONP services, allowing you access to their
content via a predefined API.
and
jQuery handles all the complex aspects of JSONP behind-the-scenes —
all we have to do is tell jQuery the name of the JSONP callback
parameter specified by YQL ("callback" in this case), and otherwise
the whole process looks and feels like a normal Ajax request.

$.ajax POST call to ServiceStack webservice, parameter not arriving

I am trying to learn how to program a web service with ServiceStack and call it via ajax in JavaScript. I did this by watching the pluralsight movies and I think I almost figured it out how to do that except for passing data as parameters with a service call.
I try to call the service with this ajax-call:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/jsonp; charset=utf-8',
url: "http://localhost:1879/entry",
dataType: 'jsonp',
data: {request: request},
success: function(result){
alert(result.Id);
}});
The service looks like this:
public class EntryService : Service
{
public object Post(Entry request)
{
return new EntryResponse() { Id = request.Amount };
}
}
[Route("/entry", "POST")]
public class Entry
{
public int Amount { get; set; }
}
public class EntryResponse
{
public int Id { get; set; }
}
I expect the alert in the callback to show the number 32, but it shows the number 0. And when I debug my service I see that request.Amount is 0 as well, so I think I do something wrong at the Ajax service call but I cannot figure out what. So I wonder what I am doing wrong here.
author of that Pluralsight course here. Hopefully I can help you.
First thing you should do is make sure the API is working correctly.
Go to this: http://localhost:1879/entry
In your web browser you should see a page displayed that has information about the service. If you don't your URL is wrong or ServiceStack is configured wrong.
Assuming the URL is correct, all you should need to do is wrap your data in JSON.Stringify().
When you do a post, the data has to be in JSON format as a JSON string. You are currently sending a JSON object.
Also, most likely you can drop the localhost bit off your url in the $.ajax call and just do "entry"
You can not do a post with JsonP. If you are trying to do a cross domain POST you need to look into cors and make sure that is enabled for the the service you are POSTing to.
Post data to JsonP
I only used jsonp cause I read and hoped that it could be the solution for my problem. But based on your explanation I shouldn't need it, so I changed my code to this:
var request = { };
request.Amount = 32;
$.ajax({ type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "http://localhost:1879/json/reply/Entry",
dataType: 'json',
data: request,
success: function(result){
alert(result.Id);
},
error: function(xhr, ajaxOptions, thrownError){
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}});
First I had this call without the error part and nothing happened, no alert, no error, nothing. So I assumed the error was consumed instead of being showed, so I added the error callback and my assumption seemed to be right. Now I get 3 alerts and the last 2 alerts shows "400" and "bad request".
I searched on those errors and tried but none of the possible solutions I found fixed my problem. I tried 2 urls: /json/reply/Entry and /entry after the localhost part but both didn't work. So what am I doing wrong?

WebMethod called through Jquery Ajax is doing 301 redirect

I have a webmethod in aspx page and I am calling it through jquery Ajax method.
In one server I am getting windows security prompt on ajax call (all other servers are working fine).
When I was checking using fiddler I see a 301 redirect of my method call(webmethods.aspx/GetDetails to webmethods.aspx/GetDetails/)
Not sure why the redirect is happening on one server and call to webmethod.aspx/GetDetails/ is throwing 401.
I checked all the wildcard mapping etc and not able to find any issues. Any idea where else I need to check?
Here is my code
$.ajax({
type: "POST",
url: "/webmethods.aspx/GetDetails",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert('success');
},
failure: function (response) {
alert(response);
},
error: function (jqXHR, textStatus, errorThrown) {
var errMessage = "An error occured serving your request. Please try again.";
if (jqXHR)
errMessage = $.parseJSON(jqXHR.responseText).Message;
alert(errMessage);
}
Can you check the handler order in your web.config? I have had similar issue where staticfile handler was before aspx handler. Changing the order fixed my issue (move the static file as the last element, because most of the time it will have verify whether file exists before handling).

Cross Domain AJAX POST 403 forbidden when attempting to execute a cs WebMethod

Pardon my noobiness in web development terminology.
I am trying to execute the following [WebMethod]:
public static void CreatePendingCaseFromChat(string userInputs)
{
//Do a bunch of stuff here with the userInputs string
}
With the following AJAX (which resides on another server):
$.ajax({ type: "POST",
url: "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat",
crossDomain: true,
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){alert("success in ajax call")},
error: function (data){alert("error in ajax call")}
});
MyCode.aspx contains the following lines within the Page_Load() method:
Response.AppendHeader("Access-Control-Allow-Origin", "*"); //Allow Cross domain AJAX call, update the "*" to be a specific URL
Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
Response.AppendHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
If I do the following, instead of the ajax call:
var invocation = new XMLHttpRequest();
var url = "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat"
if (invocation) {
invocation.open('POST', url, false);
invocation.send();
}
else {
alert("no invocation");
}
Then I can confirm with FireBug that the following Response Headers are set:
Access-Control-Allow-Head... content-type, x-requested-with
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Allow-Orig... *
With the AJAX call, none of those headers are shown.
I would like to make this work either way, whether with the AJAX call, or with the XHR call.
For the XHR call I can't figure out how to send the userInputs string to the WebMethod.
For the AJAX call I can't get it passed preflight or w/e it's called (the OPTIONS call).
I've posted a bunch of code on question:
CORS - Ajax error function reports error code as 0 for an API request returning 401
It is using MVC4, but should give you everything you need to get this working.

Can I validate an entity before saving the changes?

I have a very simple WCF Data Services application and I am doing some basic CRUD operations. I have a ChangeInterceptor on the entity set that is changing, but the object in the ChangeInterceptor is the current state in the database, not what is sent in the HTTP PUT. Is there a way to validate the properties of the object before saving it?
Here is my ChangeInterceptor:
[ChangeInterceptor("People")]
public void OnChangePerson(Person personChanging, UpdateOperations updateOperations) {
switch (updateOperations) {
case UpdateOperations.Change:
// personChanging is the database version here, not the changed version.
break;
default:
break;
}
}
Here is my client-side code (jQuery):
var data = {
FirstName: "NewFN",
LastName: "NewLN"
};
$.ajax({
type: "PUT",
url: serviceUrl + "/People(" + personID + ")",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert("Success!");
},
error: function (error) {
alert("An error occured");
}
});
Here is the JSON being sent to the server:
Here is the ChangeInterceptor when the message is received:
I have uploaded the code for this project here: http://andyjmay.com/test/2921612/ODataTest.zip
I downloaded your sample , reproed your issue and was able to see the latest updated value using this work-around for now.
While I investigate this internally,Can you change your code to use a Merge verb instead of a PUT ?
With this change, you should now be able to see the latest entity values being passed in to the ChangeInterceptors when you update the values via the jQuery client.
$.ajax({
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("X-Http-Method", "MERGE");
},
type: "POST",
url: serviceUrl + "/People(" + personID + ")",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
GetAllPeople();
},
error: function (error) {
alert(error);
}
});
WCF got some nice extension you can write like MessageInspector and ParameterInspector.
I'm sure one of them can help you validate stuff before the server even starts to work with tthe request.
If the service is EF based and the request is PUT, then the old value will be provided (this has to do with the way the EF provider is implemented and might be a bug, we will look into that some more). You can workaround this by sending a MERGE request instead. I verified, that in that case it works as expected (you get the new values). MERGE has a little different semantics, but it might work for you. PUT overwrites the entity, so if you didn't send a value for a given property it will be reset to its default value. MERGE only modifies the existing entity with the values from the payload, so if some property is not in the payload its value will be left untouched.
Hmm... you say personChanging is the database version, it should definitely be the updated version.
My tests (and people on the product team) tell me it should be the version that came over the wire. Could something else be going wrong?
For example could your property be Firstname instead of FirstName?

Categories