I have an Web API written in Core 2 that returns a FileContentResult.
You need to do a GET with an Auth Token in the header for it to work.
If you try it with postman, the file renders fine and it also renders well in an MVC View.
Now we have an external Salesforce system trying to consume the API but due to the limitations of the APEX language they have to use Javascript to inject the token into the GET method.
Example code:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'https://file-store.com/document/{! docId}',
headers: {
'Authorization': 'Bearer {! oauthToken}',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).done(function (data) {
console.log(data);
});
});
This seems to work as the "data" that is returns contains a file - or at least an array of squiggles that look like the file serialized.
However, there seems to be no way to get the web view to render this.
I tried using embed
var object = '<embed scr="' + data + '" />';
or using an iframe
$('#iFrame').html(data);
or
$('#iFrame').html(object);
and lots of other things but so far had no success.
I do understand that in MVC this is simple, but is it at all feasible using javascript?
We do successfully receive the file, and we do have the data in memory, I just need way to render it on the browser.
Any suggestion is very welcome
Related
Note: I'm using Grails 2.5.5.
This is my method in the controller (I know save() shouldn't be a GET, but I'm just testing things out):
def save(Test cmd) {
println cmd.duration
println params.duration
}
This is my client code:
let data = JSON.parse($('#req').val());
$.ajax({
url: url,
data: data,
method: 'GET',
contentType: 'application/json'
});
When this flow is executed, on the controller side, cmd.duration does not print what was sent from the client side (instead it's the default value of zero since duration is typed as an int). On the other hand, params.duration does print what was sent from the client side.
So this indicates that it's not a problem with how the data is getting sent, but instead has to do with some data binding issue?
Also, just for reference, POST works perfectly fine with the above server-side code. The command object gets populated appropriately as long as I change the client code accordingly (changing method type and stringifying the JSON):
let data = JSON.parse($('#req').val());
$.ajax({
url: url,
data: JSON.stringify(data),
method: 'POST',
contentType: 'application/json'
});
I know there are similar questions out there, but it seems like most of them deal with issues with POST requests. So this is a bit different.
Any help is appreciated!
It looks like I just needed to remove the contentType in the ajax call on the client side for the GET request. Once I did that, everything worked as expected.
Not sure if that is expected behavior, but it works for me for now.
I'm trying to post json data to my Django Rest Framework APIView.
All works well when I use the DRF api post form, but when I try with an external app (Angular2 in my case), the request.data variable is empty.
My APIView:
class CreatePaymentView(views.APIView):
def post(self, request, *args, **kwargs):
print(request.data)
return None
My urls:
url(r'payment/create', views.CreatePaymentView.as_view(), name='CreatePayment'),
My Angular2 post:
createPayment(): Observable<any> {
let body = JSON.stringify({test_data: 'whatever'});
let headers = new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.cookiesService.csrftoken,
'Authorization': `Token ${this.logged.user.token}`
});
let options = new RequestOptions({ headers: headers });
return this.http.post(environment.server_url_api + 'payment/create/', body, options)
.map(response => {
return response;
});
}
All the other posts of my app works well, but all my other views are DRF ModelViewSet, that's why I tink that my bug doesn't come from the CRFs. I suspect something is bad with my django view.
When I read the request variable in my CreatePaymentView, the data is an empty JSON instead of {test_data: 'whatever'}.
What is the good practice to send a simple POST with DRF ?
As explained in comments, it appears that the problem comes from the Visual Studio watch feature with breakpoint. Without watching the code with breakpoint, all works fine.
I'm trying to get rows that match a var, In my case a url. in the database and return the whole row as a json format.
Basically if url in table1 matches the url under eventurl in table2. Then the whole row is passed through to the ajax request as a jsonformat.
Heres what i have so far.
Routes.rb
resources :gig do
scope constraints: { format: "json" } do
get :gigdata, on: :member
end
end
In my ajax call i have this
url: 'gigdata/' + gigurlofevent , (no need to include the whole url ajax file here as its working elsewhere)
and in my controller i have this
respond_to :json, only: :gigdata
def gigdata
gig = Gigstable.where(eventurl: (params[:gigurlofevent]))
render json: gig
end
Now at the moment, I can't get into the gigdata with a byebug.
I'm wondering what i need to do/ what ive missed
Thanks
Sam
edit
Heres the start of the ajax call down the the success function
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/json");
},
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'gigdata/' + gigurlofevent ,
success: function(json) {
debugger;
Common problem:
You wrote:
(no need to include the whole url ajax file here as its working
elsewhere)
Actually you need to include complete code because common problem lays in Content-Type field. You need to specify content type of request in header like 'application/json'.
I am testing my backend api with curl
For example:
curl http://localhost/api/v1/some_action -H 'Content-Type: application/json' -vvv
Last parameter -vvv very useful to debug requests because it makes curl to output request and response with headers in console.
Another way to debug ajax
Open developer tools (for chrome it's: F12 or ctrl+shift+i), click on network tab and click on XHR filter button. Reload page with ctrl+r and execute your ajax request one more time. Information about your ajax request will appear in the window below filters. Now you can check out what kind of data comes from server and whats going wrong.
Golden rule
Rails server outputs all requests in console. Don't be shy to read output when something works not like you expected.
How can I execute a controller action in ASP.NET MVC4 sending the anti foreign key too?
My request is formed as follow code snippet:
var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;
xhr.post({
url: 'Account/LogOff',
handleAs: 'json',
contentType: 'application/json',
postData: '__RequestVerificationToken=' + _antiForeignKey
});
And I receive an error from server with a html which contains the
The required anti-forgery form field "__RequestVerificationToken" is
not present.
message as response. Obviously, the action in the controller is not executed.
I've seen this post: jQuery Ajax calls and the Html.AntiForgeryToken(), which answers my question but using jQuery.
I have got to execute the controller action by using the previous code snippet but modifying the value of two parameters, 'handleAs' and 'contentType':
var _antiForeignKey = dojoQuery('input[name="__RequestVerificationToken"]', dojo.byId('#__AjaxAntiForgeryForm'))[0].value;
xhr.post({
url: 'Account/LogOff',
handleAs: 'text',
contentType: 'application/x-www-form-urlencoded',
postData: '__RequestVerificationToken=' + _antiForeignKey
});
As you can see, I've changed the 'handleAs' property because we are not handling json data in the response, and the 'contentType' to specify we are sending other type of data as request's parameter.
I am working on an application in which i have a situation to send text data to backend through Ajax call.
But when the text "%" occurs in the text to be sent through ajax, i get the below response from my rails app
Internal Server Error
invalid %-encoding
i tried adding escape characters infrot of % symbol, but its not useful.
Any suggestion on this issue would be helpful.
Jquery ajax call used :
thanks,
Balan
You can pass jquery an object for the data option and it should correctly escape it for you:
$.ajax({
type: "POST",
url: "/controller",
data: {
text: text_from_text_area,
current_poster: current_poster
},
success: function(data){
alert(data);
}
});
See the docs here: http://api.jquery.com/jQuery.ajax/