its possible consume a spring boot api rest from JSF? - rest

I try execute a ajax query from the xhtml file, and its trows error :
Uncaught SyntaxError: Invalid or unexpected token
This is my ajax query:
<h:form>
<script type="text/javascript">
llamadaNombre();
function llamadaNombre(){
var list2=null;
$.ajax({
type : "GET",
url : "localhost:8080/users",
dataType: "json",
data: {val: list2},
success : function(result) {
$('#tablebody').html("");
$.each(result,function(key, val) {
editar="<h:commandLink action='/paginas/crud/editarCliente?dni="+val.dni+"' class='btn btn-success'> <span class='glyphicon glyphicon-search'></span> editar </h:commandLink>" ;
eliminar="<h:commandLink action='/paginas/crud//eliminarCliente?id="+val.dni+"' class='btn btn-success'> <span class='glyphicon glyphicon-trash'></span> eliminar </h:commandLink>";
var htmlrow ="<tr>"+"<td>" + val.id + "</td>"+"<td>" + val.nombre + "</td>"+"<td>" + val.apellidos + "</td>"+"<td>" + val.dni + "</td>"+"<td>" + val.correo + "</td>"+"<td>" + val.telefono + "</td>"+"<td>" + val.direccion + "</td>"+"<td>" + val.cp + "</td>"+"<td>" + val.edad + "</td>"+"<td>" + editar + "</td>"+"<td>" + eliminar + "</td>"+"</tr>";
$('#tablebody').append(htmlrow);
})
}
})
}
</script>
</h:form>
the format of data in the api rest is json
There are any way for connect api in springBoot and JSF application ? its throw the error:
jquery.min.js:2 Access to XMLHttpRequest at `'htttp://localhost:8080/users?val=' from origin 'http://localhost:9090' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.`
i Try change the port in diferents enviorments but its keep returning that error and if configure in the same port trows error that this ports its listening
this is my API controlller:(solved)
#Service
#CrossOrigin(origins = "http://localhost:8080")
public class UsuariosController {
public List<Clientes> getAll(){
return clientesFacade.getAllClientes();
}

You should add the headers param to your request as a bellow script :
$.ajax({
type : "GET",
url : "localhost:8090/users",
data: {val: list2},
headers: {
"X-Requested-With": "XMLHttpRequest",
"Authorization": .......,
},
success: function (data, text) {
console.log(data);
},
........
in your java controller, you should authorize to access from localhost in your case, you can just add the annotation : #crossorigin(origins = "localhost" ) to your service.

Related

Multipart/mixed request for google drive bulk deletion using request npm package

I was trying to do bulk deletion of files from google drive using rest API. So i was framing the request for bulk deletion request i was able to achieve the deletion with the similar request framing method Bulk delete files on Google Drive with raw XMLHttpRequest but i was trying to achieve this without sending the body instead of sending multipart array in the request object. I am getting error 400 with following response body
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
This is my request object which is failing
const _multipart = []
arrayOfFileIds.forEach((current) => {
const obj = {
body: 'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current + '\nAuthorization: Bearer ' + authToken
}
_multipart.push(obj)
})
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed'
},
multipart: _multipart
}
And below request Object is working
const boundary = 'END_OF_PART'
const separation = '\n--' + boundary + '\n'
const ending = '\n--' + boundary + '--'
const requestBody = arrayOfFileIds.reduce((accum, current) => {
accum += separation +
'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current +
'\nAuthorization: Bearer ' + authToken
return accum
}, '') + ending
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed; boundary=' + boundary
},
body: requestBody
multipart: _multipart
}
Modification points:
The access token can be included in the request header.
Put Content-Type of each batch request out of body.
When these points are reflected to your script, it becomes as follows.
Modified script:
const _multipart = [];
arrayOfFileIds.forEach((current) => {
const obj = {
"Content-Type": "application/http",
body: "DELETE https://www.googleapis.com/drive/v3/files/" + current + "\n",
};
_multipart.push(obj);
});
const requestOptions = {
url: "https://www.googleapis.com/batch/drive/v3",
method: "POST",
headers: {
"Content-Type": "multipart/mixed",
Authorization: "Bearer " + authToken,
},
multipart: _multipart,
};
Note:
When I tested the above modified script, no error occurs. The files can be deleted. When you tested the above script, when an error occurs, please confirm the script and the access token, again.
Reference:
request

devops using Ajax access query data WIQL

I am trying to access azure-devops data using Ajax. And below is my working code.
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitems/2065741?$expand=all&api-version=5.1',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
}
}).done(function( results ) {
});
After I need to access data using WQIL but it is giving an unexpected token error. I want to access WorkItem, and user activity. Can you please help with this?
$.ajax({
url: 'https://dev.azure.com/ORG/products/_apis/wit/wiql?api-version=5.1 ',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + 'XXXX')
},
JSON.Stringfy("QUERY":"SELECT [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] FROM workitemLinks WHERE " +
"( [Source].[System.TeamProject] = #project AND [Source].[System.WorkItemType] = 'User Story' ) AND ( [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' ) "+
" AND ( [Target].[System.TeamProject] = #project AND [Target].[System.WorkItemType] = 'Task' ) ORDER BY [System.Id] MODE (MustContain)")
}).done(function( results ) {
x=results
});
The previous script you are using is the method used to execute API, but not suitable for execute WIQL script. That's why you are facing that error.
Executing WIQL in Ajax is actually a request process: Send the wiql statement to the server you want to access, request to execute the query statement(Wiql), and return the execution result. Therefore, this is a process of requesting the execution of the Post command. But in your script, it did not tell the server what instructions need to be executed.
Here is the simple sample can for you refer to use WIQL with Ajax:
<script type="text/javascript">
$(document).ready(function () {
$("#SelectWIT").on("click", function () {
var d = { "query": " Select [System.Id] from WorkItems Where [System.WorkItemType] = 'Bug' "};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/{org name}/{project name}/_apis/wit/wiql?api-version=1.0',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "{PAT token}"));
},
}).done(function (data) {
var items = [];
$.each(data.workItems, function (key, val) {
items.push("<li> <a href='" + val.url + "'>" + val.id + "</a></li>");
});
$("<ul/>", {
html: items.join("")
}).appendTo("body");
}).error(function (e) {
var s = "error error error";
});
})
});
</script>
The logic of my script is to request to run a API with a WIQL statement as request body, send this request to the project I want to access. Then display the response data with js syntax into the body of the page. This is the output:
Since I am not sure what is your next operation. You can replace the Wiql statement and the Url with yours in this script. Then change the corresponding done function to achieve what you want.
Somehow WQIL is giving error 400 it looks like a permission issue.
So I Solved it in a different way. Instead of the query, there is another method which gives me all the details of the workitem I just need to pass workitem Id's in that.
var d ={
"ids": [
20813,21677
],
"fields": ["System.Id","System.WorkItemType","System.Title","System.AssignedTo","System.State","System.Tags"]
};
$.ajax({
type: 'POST',
url: 'https://dev.azure.com/ORG/products/_apis/wit/workitemsbatch?api-version=5.1',
contentType: 'application/json',
data: JSON.stringify(d),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + "XXXXX"));
},
}).done(function (data) {
x=data
});

Access TFS RESTful API from Angular web app

I think TFS RESTful api has a bug. I am trying to access it using an Angular web app. Our TFS server is corporate internal. Here is my code:
var path = 'http://tfs.mycompany.com/tfs/mycompany/_apis/wit/queries?$depth=1&$expand=all&api-version=2.2';
var config = { withCredentials: true };
$http.get(path, config)
.then(function (response) {
$scope.resultList = response.data.d.results || [ response.data.d ];
$scope.message = 'Found ' + $scope.resultList.length + ' item' + ($scope.resultList.length == 1 ? '':'s');
}, function (response) {
$scope.resultList = [];
$scope.message = 'Error ' + response.status + ' ' + JSON.stringify(response.data);
});
The request goes to the server, and the server responds with OK 200. However, the browser (Chrome) blocks the data, and tells me:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header
when the credentials flag is true. Origin 'http://localhost' is therefore
not allowed access. The credentials mode of an XMLHttpRequest is controlled
by the withCredentials attribute.
The request headers have Origin:http://localhost
The response headers have Access-Control-Allow-Origin:*
Is there any way for me to tell TFS to not return * in the Access-Control-Allow-Origin? This seems like a serious bug in TFS, which renders the RESTful api practically useless for web apps!
You may check Cross-origin resource sharing (CORS) example below to add Authorization in your code:
$( document ).ready(function() {
$.ajax({
url: 'https://fabrikam.visualstudio.com/defaultcollection/_apis/projects?api-version=1.0',
dataType: 'json',
headers: {
'Authorization': 'Basic ' + btoa("" + ":" + myPatToken)
}
}).done(function( results ) {
console.log( results.value[0].id + " " + results.value[0].name );
});
});
Also, check this case to see whether it is helpful:
AJAX cross domain issue with Visual Studio Online REST API

HTTPS request on iphone not sent to server

I am developing an application for iphone using phonegap.
When submitting ajax requests using HTTP everything works fine. But when i switch to HTTPS, the requests aren't sent to the server. The same code works for HTTP and HTTPS on android.
Below is the code i am using, thank you for your help in advance
var xmlRequest = $.ajax({
url : "https://test.com",
type : 'POST',
contentType : "text; charset=utf-8",
data : sr,
dataType : "text",
headers : { SOAPAction : '"'+soapaction+ '"' },
success : function( data, textStatus, jqXHR ) {
console.log("----- xmlRequest.responseText: " + xmlRequest.responseText);
SOAPClient._onSendSoapRequest(method, async, callback, sch, data);
},
error : function( jqXHR, textStatus, errorThrown ) {
console.log("----- xmlRequest.responseText: " + xmlRequest.responseText);
console.log("----- errorThrown = " + errorThrown + " textStatus = "+ textStatus );
ServiceErrorMessage(method, jqXHR.status, errorThrown, xmlRequest.responseText);
},
cache: false
});
Add this to the end of your AppDelegate.m file
#implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host
{
return YES;
}
#end

IPhone PHONEGAP- Https ajax for datatype - XML

I'm trying to get XML response from a secure https URL using Jquery AJAX call...
I'm getting the following error. Can anyone help me with the issue?
Unauthorized user
Here is my code
$.ajax({
type : "GET",
url : url + "?" + params,
error : function(jqxhr, status, error)
{
alert(status +"....."+error);
},
success : function(data, textStatus, jqxhr) {
var xmlDoc = jqxhr.responseText;
alert(xmlDoc);
}
});
Definitely need more details, but if you're sending a request to a secure url, you likely need to pass some kind of value to show you're logged in or some-such, like a cookie value. To pass a value, you may need to use the headers option:
$.ajax({
type : "GET",
url : url + "?" + params,
headers : {"COOKIE", "userID=h3j5o273h4"},
error : function(jqxhr, status, error)
{
alert(status +"....."+error);
},
success : function(data, textStatus, jqxhr) {
var xmlDoc = jqxhr.responseText;
alert(xmlDoc);
}
});