I have a JS calling a Python function. Here is the JS call :
fetch('/ws/invoice/checkDoublon', {
method : 'POST',
headers : {
'Content-Type': 'application/json'
},
body : JSON.stringify({
'invoiceNumber' : invoiceNumber.val(),
'vatNumber' : vatNumber.val(),
'id' : $('#pdfId').val()
})
}).then(function(response) {
console.log(response)
});
My Python code is like this (i'm using Flask) :
#bp.route('/ws/invoice/checkDoublon', methods=['POST'])
#login_required
def checkInvoiceDoublon():
if request.method == 'POST':
data = request.get_json()
invoiceNumber = data['invoiceNumber']
vatNumber = data['vatNumber']
invoiceId = data['id']
_vars = init()
_db = _vars[0]
_cfg = _vars[1].cfg
# Check if there is already an invoice with the same vat_number and invoice number. If so, verify the rowid to avoid detection of the facture currently processing
res = _db.select({
'select' : ['rowid, count(*) as nbInvoice'],
'table' : ['invoices'],
'where' : ['supplier_VAT = ?', 'invoiceNumber = ?'],
'data' : [vatNumber, invoiceNumber]
})[0]
if res['nbInvoice'] == 1 and res['rowid'] != invoiceId or res['nbInvoice'] > 1 :
return 'Duplicate', 200
else:
return 'Not duplicate', 200
All of this works but the console.log(response) doesn't show at all the custom return I want from Python "Not duplicate" or "Duplicate". It only show OK as response.statusText because I return the HTTP code 200
How could I retrieve a custom message on my JS code ? It could be great if it's using fetch and not ajax
Thanks in advance
this is because fetch return a Response on which you need to call either .text() or .json() the two returning a Promise containing your data as an object or a string depending on the one you've chosen
your js would look something like this
fetch('/ws/invoice/checkDoublon', {
method : 'POST',
headers : {
'Content-Type': 'application/json'
},
body : JSON.stringify({
'invoiceNumber' : invoiceNumber.val(),
'vatNumber' : vatNumber.val(),
'id' : $('#pdfId').val()
})
}).then(function(response) {
response.json().then(function(data) {
// here data is the object containing your datas
})
// or
response.text().then(function(value) {
// here value is the string returned by your python script
let data = JSON.parse(value) // this line transform the string into the same object you get by calling .json() above
})
});
You need to return a valid JSON Response from your Flask backend
You can take it in a promise pipe line and extract all data :
The python server for my code is this
Related
I'm using the below function in Jenkins Shared Library.
/* The below function will list the groups */
def list_groups(server_url,each_group_name,authentication){
def groups_url = server_url + "/api/v1/groups"
def response = httpRequest consoleLogResponseBody: true,
contentType: 'APPLICATION_JSON',
customHeaders: [[maskValue: false, name: 'Authorization', value: authentication]],
httpMode: 'GET', ignoreSslErrors: true, responseHandle: 'NONE', url: groups_url,
validResponseCodes: '100:599'
if(response.status == 404){
throw new Exception("Server url not found! Please provide correct server URL.")
}
else{
if(response.status == 400 || response.status == 403){
throw new Exception("Invalid Access token or Access token expired!")
}
}
def result = readJSON text: """${response.content}"""
}
=====================================================================
I'm getting the below response,
Response Code: HTTP/1.1 200 OK
Response:
[{"id":2,"name":"Default User"},{"id":3,"name":"fos"},{"id":4,"name": "kXR"},{"id":5,"name": "Sgh"},{"id":6,"name":"ksn"},{"id":7,"name":"ALb"}]
Success: Status code 200 is in the accepted range: 100:599
Requirement:
I need to get the last output from the JSON body (id & name) ---> {"id":7,"name":"ALb"} from the response and to be printed and stored in a variable using groovy.
First, you need to Parse the response String to a JSON object, for this you can either use Jenkins native method readJSON, or something like JsonSlurperClassic. Then you can use JSON path expressions to extract the values. Check the following example.
def jsonObj = readJSON text: response.getContent()
def id = jsonObj.id[-1]
def name = jsonObj.name[-1]
echo "ID: $id | NAME: $name"
I have created an API call in excel to get data from a Wix database.
The call:
Dim http As Object, JSON As Object
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "https://username.wixsite.com/mysite/_functions/Functionname", False
http.setRequestHeader "Authorization", "myauthkey"
http.Send
MsgBox (http.responseText)
The javascript http backend file on Wix:
import { ok, notFound, serverError } from 'wix-http-functions';
import wixData from 'wixdata';
export function get_Wixdata() {
let options = {
"headers": {
"content-type": "application/json"
}
};
return wixData.query("wix data collection name")
.find()
.then(results => {
if (results.items.length > 0) {
options.body ={
"items": results.items
}
return ok(options);
}
})
}
I tested the call (without authorisation) on JSON place holder and it worked fine.
Just trying to debug what's happening as I am getting "" as a response.
Even if I enter the wrong API key I still get "", even a wrong url it's still a "" response.
I take it I am clearly way off the mark with what I am trying to do..
Did you tried put both headers in your request, like the following:
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': '....'
});
The issue was with the VBA call, the header was not needed.
Dim https As Object, JSON As Object
Set https = CreateObject("MSXML2.XMLHTTP")
With CreateObject("Microsoft.XMLHTTP")
.Open "GET", "end point url", False
.send
response = .responseText
End With
So first I'm new to ajax and JSON http get request, etc. I try to use the new Twitch API to get information about streamers.
var token = $.ajax({
'url' : 'https://api.twitch.tv/kraken/oauth2/token?client_id=XXX&client_secret=XXX&grant_type=client_credentials',
'type' : 'POST',
'success' : function(data) {
console.log(data.access_token);
localStorage.setItem('token', data.access_token)
}
});
var test = $.ajax({
headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')},
'url' : 'https://api.twitch.tv/helix/users?login=nightbot',
'type' : 'GET',
'success' : function(data) {
console.log(data); // returns an obj with an data array, length 1
console.log(data[0]); // undefined
console.log(data.display_name); // undefined
console.log(JSON.parse(data)); // syntax error
console.log(JSON.parse(data[0])); // syntax error
//$( "#result" ).load( data.display_name ) //to do
}
});
DATA: https://i.imgur.com/J3R7PNu.png
I think that this way is a bit messed up. Is is?
My second problem is, that I can't access the data from the GET REQUEST. The output shows me that there is data but somehow I can't access it and I don't know why.
The output shows me that there is data but somehow I can't access it and I don't know why
As per the OP statement :
console.log(data); // returns an obj with an data array, length 1
Hence, to access the array first element you should use below statement.
console.log(data.data[0]);
You need to understand how AJAX call works, the first $.ajax call executes a request and immediately the $.ajax call is executed and your data within localStorage will be inconsistent.
Execute from your first $.ajax call the second process https://api.twitch.tv/helix/users?login=nightbot.
This way your calls are consistent and will share a consistent data within localStorage.
Twitch /users endpoint
According to the Twitch documentation (/users endpoint), the response follows this structure:
{
"data": [
{
"_id": 45454
"display_name": "Ele"
.
.
.
.
}
]
}
So, you have to access that array as follow:
console.log(data.data[0].display_name);
Lool this code snippet, the first $.ajax call executes a function called executeUserProess.
var token = $.ajax({
'url': 'https://api.twitch.tv/kraken/oauth2/token?client_id=XXX&client_secret=XXX&grant_type=client_credentials',
'type': 'POST',
'success': function(data) {
console.log(data.access_token);
localStorage.setItem('token', data.access_token);
executeUserProess();
}
});
var executeUserProess = function() {
var test = $.ajax({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('token')
},
'url': 'https://api.twitch.tv/helix/users?login=nightbot',
'type': 'GET',
'success': function(data) {
console.log(data); // returns an obj with an data array, length 1
console.log(data.data[0].display_name);
//$( "#result" ).load( data.display_name ) //to do
}
});
};
An AngularJS app needs to retrieve a JSON object from a REST service called from a Spring Boot back end. How do I modify the code below so that the response can be parsed into the properties of the returned JSON object?
For example, I will want to extract the firstname, lastname, and other properties from the JSON object after it is returned.
Here is the AngularJS controller that calls the REST service:
angular.module('confirm', []).controller('confirm', function($scope, $http, $routeParams) {
// set the default value
$scope.confirmStatus = "blank";
$scope.$on('$viewContentLoaded', function() {
var str1 = "/confirm-email?d=";
var str2 = $routeParams.d;
var res = str1.concat(str2);
var fnm3 = "nothing";
$http.post(res).then(function(response) {
fnm3 = response.data.firstname;//this line halts the program
//replacing with following line doesn't work.
//$scope.weblead = response.data;
});
$scope.confirmStatus = "success";
document.write(fnm3);
});
});
And here is the Spring Boot method that delivers the JSON response:
#RequestMapping(value = "/confirm-email", method = RequestMethod.POST)
public #ResponseBody WebLead confirmEmail(HttpSession session, #RequestParam(value="d") String dval) {
WebLead dummy = new WebLead();dummy.setFirstname("justAtest");
try{
System.out.println("The Server Heard The registration form Request!");
System.out.println("dval is: "+dval);
String sid = session.getId();
System.out.println("session id is: "+sid);
try{
List<WebLead> wleads = myrepo.findBySessionid(dval);
if(wleads.size()>0){//replace with better handling later
System.out.println("wleads.size is > 0 !");
wleads.get(0).setEmailConfirmed("true");
myrepo.save(wleads.get(0));
return myrepo.findBySessionid(dval).get(0);
}
return dummy;
} catch(Exception e){return dummy;}
} catch(Exception e){return dummy;}
}
NOTE: We know that the post was processed at the server, because the terminal logs starting with the SYSO in the /confirm-email handler are:
The Server Heard The registration form Request!
dval is: a1b2c3
session id is: E1F844262F254E9B0525504723DBA490
2016-01-07 12:11:49.773 DEBUG 7288 --- [nio-9000-exec-9] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] tRepository$SaveToSessionResponseWrapper : Skip invoking on
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2016-01-07 12:11:49.774 DEBUG 7288 --- [nio-9000-exec-9] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
You can use JSON.parse(jsonData). Here is an example that should get you there.
$http.post(res).then(function(response) {
$scope.data = JSON.parse(response.data);
fnm3 = $scope.data.firstname;
});
Also, when I am working with the REST service I have, I like to put console logs in the function when debugging and then I remove them before I finish. This gives you an easy way to see what the service gave you back.
$http.post(res).then(function(response) {
console.log(response);
});
First of all i wouldn't recommend building your own strings with parameters when doing requests with angular. You can simply do something like this:
$http({
method: 'POST',
url: '/confirm-email',
headers: {
'Content-Type': 'application/json'
},
params: {
d: $routeParams.d
}
}).then(function(response) {
...
});
Secondly if you put the content-type header like above to "application/json" and if the server supports it, then angular will JSON.parse your data automatically and simply return a javascript object to you as response.data.
And the third and last problem is that your content will never display the given data in your code, because the POST call is asynchronous, but document.write the content of the variable fnm3 immediately after firing the request.
You have two options to fix this:
(Fast, easy, but bad) do a second document.write WITHIN the callback of your post-request
(The correct way) Define your value on the angular-scope instead:
$scope.fnm3 = response.data.firstname;
and define a corresponding template to do some angular two-way-binding magic with it, like:
Firstname: {{ fnm3 }}
For the purpose of writing less code and more efficiency and in order to make reusability of calling services (since you call your services in multiple pages) use the following code :
App.service("metaService", function ($http,$cookies) {
this.CallService = function (verb, serviceName, Data) {
var Url = BaseURL + serviceName;
switch (verb) {
case "get":
{
return $http({
method: verb,
url: Url
, headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': '*/*',
}
});
break;
}
case "post":
case "put":
case "delete":
{
return $http({
method: verb,
url: Url,
data: Data
, headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': '*/*',
}
});
break;
}
}
}
});
then you can call callservice method like so
var SearchData = metaService.CallService1(method, "meta/selectAll", searchedMeta);
SearchData.success(function (data) {
$scope.Title = data.Title
}
I am making simple Spring MVC web application. In my application I want to send a object from front end to Spring controller method. But when I do this I am getting js error
500 (Internal Server Error)
I tried to find a good answer in internet but still could not find a good one.
My controller method is
#RequestMapping(value = "/add", method = RequestMethod.GET, consumes = { MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public #ResponseBody String addInventory(#RequestBody InventoryAddParam inventoryAddParam) {
log.info("addInventory");
ServiceRequest<InventoryAddParam> serviceRequest = convertAddParamtoServiceRequest(inventoryAddParam);
validate(inventoryAddParam);
inventoryService.addInventory(serviceRequest);
return "Inventory Added Succesfully";
}
inventoryAddParam is a Serializable object that contain only String parameters.
My JavaScript function to send object is
function sendDataTest() {
$.ajax({
url : "/GradleSpringMVC/inventory/add",
type : 'GET',
dataType : 'json',
data : JSON.stringify(populateTestObject()),
contentType : 'application/json',
mimeType : 'application/json'
}).done(function(data) {
// temGrid.addJSONData(data);
}).fail(function(error) {
// parseToPageAlerts(error.responseText);
}).always(function() {
// hideLoading()
});}
I am creating the addParam object to send as ajax call.
It create in function
function populateTestObject(){
var addParam = new InventoryAddParam();
addParam.inventoryId = "INV001";
addParam.name = "ECG MACHINE";
addParam.price = "1000";
addParam.hospital = "Colombo";
addParam.userNote = "User Note";
return addParam;}
Do I have done any wrong thing here ?
Other details about the error
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/GradleSpringMVC/inventory/add
Request Method:POST
Status Code:500 Internal Server Error
Header
Connection:close
Content-Language:en
Content-Length:4939
Content-Type:text/html;charset=utf-8
Date:Wed, 21 Jan 2015 03:55:19 GMT
Server:Apache-Coyote/1.1
You spring method consumes application/json and the error message says that what you're sending is not a valid JSON.
Following that line, I believe that your issue is a $.extend(addParam), when set with a single argument it will extend a jQuery namespace with the object, and won't return any JSON object to be stringified (and nothing being sent to the server). The possible solution is either removing the extend function, or adding another parameter in which case a valid JSON object will be returned, e.g.
function sendData() {
var addParam = createAddParam();
$.ajax({
url : "/GradleSpringMVC/inventory/add",
type : 'GET',
dataType : 'json',
data : JSON.stringify(addParam),
contentType : 'application/json',
mimeType : 'application/json'
}).done(function(data) {
// temGrid.addJSONData(data);
}).fail(function(error) {
// parseToPageAlerts(error.responseText);
}).always(function() {
// hideLoading()
});}
Found the answer. Just changed the version of jackson to 1.9.12
'org.codehaus.jackson:jackson-mapper-asl:1.9.12'