IBM Worklight - "Failed to parse the payload from backend" - ibm-mobilefirst

Must any URL of RSS resource end with ".xml" when used in Worklight?
For example: http://www.youku.com/user/rss/id/24645394
I tried to save the above as an XML file, then place it in my localhost. It works. However, the below code doesn't work... I get the following invocation result.
Do you you have solution about my case?
{
"errors": [
"Premature end of file.",
"Failed to parse the payload from backend (procedure: HttpRequest)"
],
"info": [
],
"isSuccessful": false,
"responseHeaders": {
"Accept-Ranges": "bytes",
"Age": "0",
"Cache-Control": "no-store, no-cache, must-revalidate",
"Connection": "close",
"Content-Length": "0",
"Content-Type": "text\/html; charset=utf-8",
"Date": "Mon, 07 Apr 2014 16:24:45 GMT",
"Server": "Varnish",
"X-Cache": "Miss from 1.w.b28"
},
"responseTime": 2452,
"statusCode": 404,
"statusReason": "Unknown virtual host",
"totalTime": 2465,
"warnings": [
]
}
News.xml
<?xml version="1.0" encoding="UTF-8"?>
<wl:adapter name="News"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wl="http://www.worklight.com/integration"
xmlns:http="http://www.worklight.com/integration/http">
<displayName>News</displayName>
<description>News</description>
<connectivity>
<connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
<protocol>http</protocol>
<domain>www.youku.com</domain>
<port>80</port>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="2" />
</connectivity>
<procedure name="getStories" />
<procedure name="getStoriesFiltered" />
</wl:adapter>
News-impl.js
function getStories(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path
};
return WL.Server.invokeHttp(input);
}
function getStoriesFiltered(interest) {
path = getPath(interest);
var input = {
method : 'get',
returnedContentType : 'xml',
path : path,
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
return WL.Server.invokeHttp(input);
}
function getPath(interest) {
if (interest == undefined || interest == '') {
interest = '/user/rss/id/24645394/';
}else {
interest = '/user/rss/id/'+interest;
}
return interest;
}
filtered.xsl
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:h="http://www.w3.org/1999/xhtml">
<xsl:output method="text"/>
<xsl:template match="/">
{
'Items': [
<xsl:for-each select="rss/channel/item">
{
'title': '<xsl:value-of select="title"/>',
'link': '<xsl:value-of select="link"/>'
},
</xsl:for-each>
]
}
</xsl:template>
</xsl:stylesheet>

add host header:
var input = {
method : 'get',
returnedContentType : 'xml',
path : path,
headers: {
"Host":"www.youku.com"
}
};

Related

VueJS and Axios handle errors properly

I am trying to raise an error during the login ... but weird thing is -> it does not work as I would expect it to ...
I am having this simple auth.service.js
class AuthService {
async login(params) {
try {
const user = (await axios.post('/authentication', { ...params })).data;
return true;
} catch (err) {
console.log(err);
throw new Error(err);
}
}
}
export default new AuthService();
The "err" has the full axios error object (as shown below)
{
"message": "Request failed with status code 401",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 401\n at settle (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1124:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1335:7)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"baseURL": "http://localhost:3030",
"method": "post",
"url": "/authentication",
"data": "{\"username\":\"admin\",\"password\":\"admin\",\"strategy\":\"local\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 401
}
what is weird is, that when I use that in my login method .. I am getting just the name and message values ... nothing else :(
methods: {
async login() {
const payload = { username: this.username, password: this.password, strategy: 'local' };
AuthService.login(payload)
.then(() => {
this.$router.push({ name: 'home' });
this.loading = false;
})
.catch(error => {
console.log(error); // THIS DOES NOT SHOW THE ENTIRE OBJECT WITH ALL KEYS
this.loading = false;
});
},
any idea why?

Modifying a fetch request for vuejs

I am new to using a fetch request with vue. I have a fetch request that works great, but want to modify the properties to use the data that is found in the model. Right now it hardcodes everything in it, but need some properties to be dynamic for instance like if the title comes from an input field or if the referral code comes from a cookie.
new Vue({
el: "#app",
data: {
title:"jjj",
kol_referrer:localStorage.getItem('shell'),,
url:"https%3A%2F%2Fshared%2Fdoggo%2520(2).png"
},
methods: {
submit: function(){
fetch("", {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin"
},
"referrer": "",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "title=jjj&url=https%3A%2F%2Fshared%2Fdoggo%2520(2).png&opensInNewWindow=1&isXhr=true&requestId=2&kol_referrer=LxOfRIA4TdeWTYA0rT96AGz",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
<button v-on:click="submit">Click</button>
</div>
Simply use templates litterals with backticks :
submit: function() {
let myTitle = "myTitle"
let myKolReferrer = "foo"
fetch("", {
"headers": {
"accept": "*/*",
"accept-language": "en-US,en;q=0.9",
"content-type": "application/x-www-form-urlencoded",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"96\", \"Google Chrome\";v=\"96\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin"
},
"referrer": "",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": `title=${myTitle}&kol_referrer=${myKolReferrer}`,
"method": "POST",
"mode": "cors",
"credentials": "include"
});
}

React Native fetch() not outputting body in console log

I am using fetch() to get some data from an API. When testing in Postman the data is returned successfully as JSON. However, when testing from react native app on android I get a text/html response, not sure why. How can I view the body of the response from the text in console.log() to debug? When I do console.log(resp) I can not see the body.
const response = await fetch('https://web.com/api/usersignup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(resp => {
this.setState({spinner: false});
console.log(resp);// output in console is pasted under this code
return resp.text();
//return resp.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Output I get in Metro Builder when using console.log(). Does not include body.
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"headers": Headers {
"map": Object {
"cache-control": "public, max-age=0",
"connection": "keep-alive",
"content-length": "0",
"content-type": "text/html; charset=UTF-8",
"date": "Sat, 09 Nov 2019 21:06:05 GMT",
"server": "Apache",
"x-ratelimit-limit": "60",
"x-ratelimit-remaining": "59",
},
},
"ok": true,
"status": 200,
"statusText": undefined,
"type": "default",
"url": "https://web.com/api/usersignup",
}
You cannot print the body until the promise of first then is finished.
I made an example with your code: https://snack.expo.io/#egizas/fetch-print-body
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//body: JSON.stringify(formData)
})
.then(resp => {
console.log('Printing out not json');
console.log(resp);
return resp.json();
})
.then((responseJson) => {
console.log('Printing out json');
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Just replace the endpoint and provide correct header.

protractor GET and PUT API call

I want to do API call in my protractor test case inside beforeAll() function and once I get the promise return my Test cases should start running. as my test cases are heavily dependent on API response.
I tried using jQuery however it is showing 'jQuery is undefined.' I am using protractor5.3.0.
var data ={
"request": {
"urlPattern": "/portal/user/profile",
"method": "GET",
"headers": {
"Accept": {
"contains": "application/json"
},
"Content-Type": {
"contains": "application/json"
}
}
},
"response": {
"bodyFileName": "abc.json",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "{{request.headers.Origin}}"
},
"transformers": [
"response-template"
]
}
};
function setUserProfile(profile, data){
var id;
if(data) {
data.response.bodyFileName = "abc.json";
}
jQuery.ajax({
url: "someurl",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(result) {
result.mappings.forEach(function(mappingItem) {
if(mappingItem.request.urlPattern === '/portal/user/profile') {
id = mappingItem.id;
}
});
jQuery.ajax({
url: "someurl",
type: 'PUT',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
console.log("success?", result);
}
});
}
});
}
describe('Logout Page', function () {
var userDropdownEle;
beforeAll(function () {
request('someurl', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
userDropdownEle = element(by.css(logoutSelectors.dropDownButton));
xchangePageObject.getLoginUrl();
});
});

How Parsing javascript vars to PHP in Datatable

I'm new in datatables and sorry for my bad english.
I really need your help to help solve my problem.
So, my code is all in one page :
$( function () {
var oTable;
function fnFormatDetails( nTr ) {
var aData = oTable.fnGetData(nTr);
sOut = "<?php foreach($this->m_rumah_sakit->getStyleAndCount(280)->result() as $style){
echo $style->keterangan; ?>
<br /> 1. Yes : ( <i><?php echo ($style->yes)?$style->yes:'0'; ?> Ulasan </i>)
<br /> 2. No : ( <i><?php echo ($style->no)?$style->no:'0'; ?> Ulasan</i> )
<br /> 3. Not Sure : ( <i><?php echo ($style->not_sure)?$style->not_sure:'0'; ?> Ulasan</i> ) <br /><?php } ?>";
return sOut;
}
$(document).ready ( function() {
oTable = $('#tSortable').dataTable({
"bProcessing": true,
"bServerSide": true,
"aaSorting": [[1,'asc']],
"oLanguage": {"sProcessing": "<img src=" + vars.loader + ">"},
//"sAjaxSource": "../details_col.php",
"sAjaxSource" : base + "cms-ajax-data",
"fnServerParams" : function ( aoData ) {
aoData.push(
{ "name": "p", "value" : "" },
{ "name": "hRating", "value" : "hospital" }
,{ "name": "c", "value" : vars.column }
,{ "name": "iC", "value" : vars.indexColumn }
,{ "name": "t", "value" : vars.table }
,{ "name": "w", "value" : vars.where }
,{ "name": "imp", "value" : vars.implode }
);
},
"aoColumnDefs": [{"bSortable":false,"bSearchable":false, "sClass": "hidden", "aTargets":[1]}]
});
$('#tSortable tbody td img').live('click',function(){
var nTr = this.parentNode.parentNode;
if(this.src.match('details_close')){
this.src = "..//details_open.png";
oTable.fnClose(nTr);
}else
this.src = "../details_close.png";
oTable.fnOpen(nTr,fnFormatDetails(nTr),'details');
}
});
});
And all works like charms! the only problem is : how i can get variable aData[2] in PHP script?
I mean, how to call it like this in my PHP code :
foreach($this->m_rumah_sakit->getStyleAndCount("+aData[2]+")->result();
Hope you understand what I mean. Thanks for any advise.