zombie.js xhr json always fail - javascript

I want to use zombie js to test my little node app.
I'm using the mock ressoures with zombie but when i write
body: object
in mock.the xhr always fail because of
Request Failed: parsererror, SyntaxError: Unexpected token o
when i write
body: 'json content'
xhr work well
To test this client js
var xhrGetRiver = $.getJSON("api/1/settings/rivers/fs/")
xhrGetRiver.done(function(json) {
console.log(json);
$.each(json, function(index, fsriver) {
insertFSRiver(fsriver);
});
});
xhrGetRiver.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
I have write this test
var data = [];
var json = {
"id": "test",
"properties": {
"url": "/tmp",
"server": "192.168.9.2",
"port": 22,
"username": "testUser",
"password": "test",
"protocol": "ssh",
"update_rate": "15m",
"includes": "*.docx"
}
};
data.push(json);
this.browser.resources.mock('/api/1/settings/rivers/fs/', {
statusCode: 200,
headers: { 'ContentType': 'application/json' },
body: data // xhr fail
//body: '[ { "id":... ... } ]' // Work well

in app i'am using Express framework and i use res.json the array from library.
res.json seem to stringify my array

Related

Try to execute js script in manifest to ask privatte API with post request

I try to use js script in my jps to test credentials with a personal APi. The idea is to return an error code in the jps if credentials are false. In my computer my js script works fine but when i try to start my jps with this i have an javascript error.
my jps:
onInstall:
- script [*]: https://github.com/user/project/blob/master/script.js
responses:
401:
type: error
message: bad credentials
My js script:
const https = require('https')
var name = "some-name"
var password = "some-password"```
const data = JSON.stringify({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
})
const options = {
hostname: 'mYapi.com',
port: 443,
path: 'mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
var req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res.statusCode)
return res.statusCode;
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I get this error in the console :
ERROR: script.response: {"result":1704,"line":50,"response":null,"source":"hx-core","time":122,"error":"org.mozilla.javascript.EvaluatorException: syntax error"}
And i try a lot of differents script to do this post request ----> works in my computer ( api send result 201 if credentials are good and 401 if not ) , -----> doesn't work in jelastic manifest.
So please can you explain me how i can do a post request with json on my API in Jelastic manifest ( js call script ). I thank you in advance !
The code that is executed by the "script" action runs on the JVM therefore it allows you to connect and use Java libraries.
To implement a POST request and determine the status of the output code, you can use Commons HttpClient.
See below for an example.
type: install
name: HttpClient Post
onInstall:
- script: |
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
var client = new HttpClient();
var name = "some-name";
var password = "some-password";
var requestEntity = new StringRequestEntity(toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
}), "application/json", "UTF-8");
var post = new PostMethod("https://example.com/");
post.setRequestEntity(requestEntity);
var status = client.executeMethod(post);
post.releaseConnection();
if (status == HttpStatus.SC_CREATED) { // 201
return { type : "success" };
} else if (status == HttpStatus.SC_UNAUTHORIZED) { // 401
return { type: "error", message: "bad credentials" };
}
return { type: "error", message: "unknown error" };
Also, you can find many useful examples and information in the Jelastic JPS Collection repository.
Perhaps the next script will be useful for you:
https://github.com/jelastic-jps/git-push-deploy/blob/master/scripts/add-web-hook.cs
One last thing that if you don't need the exact HTTP Status, you can use an integrated "Transport" class.
import com.hivext.api.core.utils.Transport;
var name = "some-name";
var password = "some-password";
var data = toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
});
try {
new Transport().post("https://example.com/", data, {
'Content-Type': 'application/json',
'Content-Length': data.length
});
return { type: "success" };
} catch (e) {
return {
type: "error",
message: "unknown error: " + e
};
}

Trying to create multisig account for NEM on local machine but getting error

Hello Everyone I am trying to make plugin from Buildfire to be bale to create NEM account and to change it into multisig account using local network (ei localhost)
Here are the code snippets for the required things I would like to ask weather there is an issue in making of JSON missing bits in the json or any other errors I need to look up, I have tried to look up error and it's solution but met with no results. The error I get is :
"error: "Internal Server Error" message: "expected value for property
transaction, but none was found" status: 500"
let done = $.ajax({
url: "http://127.0.0.1:7890/account/generate"
}).done(function (data) {
/// check you have data to report on
///if (data && data.list && data.list.length) {
/// fill in the UI with the new data
var report = data;
PubKey = report.publicKey;
PKey = report.privateKey;
$('#address').text("Created Account");
$('#balance').text(report.address);
$('#summary').text(report.privateKey);
$('#vested').text(report.publicKey)
///}
});
var date = new Date();
var TS = date.getTime();
var xyz = {
xyz: JSON.stringify({
"transaction":
{
"timeStamp": TS, ///needs to be changed to current timestamp from creating of account
"fee": 20, ///have to check
"type": 4097,
"deadline": TS + 30000, ///need to be changed
"version": -1744830462, /// main(real) network 1744830465,
"signer": PubKey,
"modifications": [
{
"modificationType": 1,
"cosignatoryAccount": PbKey
}
],
"minCosignatories" : {
"relativeChange": 1
}
},
"privateKey": PKey
})
};
fetch("http://127.0.0.1:7890/transaction/prepare-announce",{
method : 'POST',
headers : {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body : JSON.stringify(xyz)
}).then(function (response) {
return response.json();
})
.then(function (result) {
alert(result);
}).catch (function (error) {
console.log('Request failed', error);
});
did you try normal transaction?
It looks you don't sign your transaction.
and DON'T FETCH YOUR PRIVATE KEY ON NETWORK.

Code by Zapier Get Unexpected Token When Inserting InputData variable into JSON string

Have been trying to insert inputdata.SKU into the payload below. However, I get Unexpected Token error.
Complete Javascript code used in the Code by Zapier input box is below. Note have replaced the token with XXXXXXX in endpoint variable for security reasons.
var endpoint = 'https://api.yotpo.com/apps/XXXXXX/purchases/';
var payload = {
"validate_data": true,
"platform": "general",
"utoken": inputData.ACCESS_TOKEN,
"email": inputData.EMAIL,
"customer_name": inputData.CUST_NAME,
"order_id": inputData.ORDER_ID,
"order_date": inputData.ORDER_DATE,
"currency_iso": "NZD",
"products": {
inputData.SKU : {
"url": inputData.URL,
"name": inputData.NAME,
"image": inputData.IMAGE_URL
}
}
};
fetch(endpoint, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(payload)
}).then(function(response) {
return response.text();
}).then(function(responsebody) {
var output = {response: responsebody};
callback(null, output);
}).catch(function(error) {
callback(error);
});
It looks like you're using an expression, inputData.SKU, as a property name (key). Luckily, Zapier runs on node.js v4.3.2, so computed property names are supported.
Try changing that line to this (wrap the expression in brackets):
[inputData.SKU] : {

Error 400 : Required parameter part

Iam trying to use youtube api for finding the information about a particular video using youtube api.I have used the https module for sending and receiving data
This is the code I have used
var youtube_query=querystring.stringify({
q:'bangarang',
key:'api_key',
part:'snippet'
});
var options_you = {
host:'www.googleapis.com',
method:'GET',
path:'/youtube/v3/search'
};
function getvid_id(vid_result){
//callback function for finding the information on the video
vid_result.setEncoding('utf8');
console.log("STATUS :"+vid_result.statusCode);//to show the status code
vid_result.on('data', function (body) {
console.log(body);
});
}
var youtube_request = https.request(options_you,getvid_id);
youtube_request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
youtube_request.write(youtube_query);
youtube_request.end();
However I get the following response
STATUS :400
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter: part",
"locationType": "parameter",
"location": "part"
}
],
"code": 400,
"message": "Required parameter: part"
}
}
As you can see ,I have already provided the part parameter.But I cannot find the reason why it is not working .
You can pass querystring directly to the path field as :
var querystring = require("querystring");
var https = require("https");
var youtube_query = querystring.stringify({
q: 'bangarang',
key: 'api_key',
part: 'snippet'
});
var options_you = {
host: 'www.googleapis.com',
method: 'GET',
path: '/youtube/v3/search?' + youtube_query
};
var youtube_request = https.request(options_you, function(res) {
res.on('data', function(d) {
process.stdout.write(d);
});
});
youtube_request.end();

EWS - A token was not recognized in the JSON content

I try to send an email via EWS using Javascript and the REST API.
The OAuth is not the problem so far.
The problem is, if I try to send the email, the Server sends this response:
"{"error":{"code":"RequestBodyRead","message":"Invalid JSON. A token was not recognized in the JSON content."}" (taken from Chrome Debug Console).
Here my Javascript, where the error occurs:
function mailIsRaus(token) {
var gottenParam = JSON.stringify(token);
var jsonObj = JSON.parse(gottenParam);
var leToken = jsonObj['access_token'];
//This is the Token from Active Directory
leToken = "Bearer " + leToken;
var Message = {
"Message": {
"Subject": "TESTING REST API EWS",
"Body": {
"ContentType": "Text",
"Content": "IT WORKED. The EWS is working my friend."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "johndoe#something.com"
}
}
]
},
"SaveToSentItems": "true"
};
//eMailData = JSON.stringify(eMailData);
$.ajax({
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Authorization", leToken);
request.setRequestHeader("Content-Type", "application/json");
},
data: Message,
url: 'https://outlook.office.com/api/v2.0/me/sendmail',
success: function (e) {
console.log('Email sent');
console.log(e);
},
error: function (message) {
console.log(message);
}
});
}
I strictly sticked to MSDN and now, I have no clue, why this error occurs.
If I comment out the "setRequestHeader" I get an error 401 unauthorized.
The token ist correct.
The scope is also correct.
Maybe I made an simple mistake in the "var Massage" or something...
I found the solution by myself.
I had to uncomment the following line of code to:
eMailData = JSON.stringify(eMailData);
Now it is working fine.

Categories

Resources