I am inserting data to table of parse.
I have import Parse from 'parse/node'; on the top.
And inserting the data like :
const game = Parse.Object.extend('Game');
const query = new Parse.Query(game);
query.set('name', 'Delta');
query.save(null, {
success(DOD) {
console.log('Success');
},
error(DOD, error) {
console.log('Failed');
},
});
It throws error :
TypeError: query.set is not a function.
What am i missing ?
This method is simply not available. See API Parse
Related
I am dealing with JavaScript error in Terra.js.
Can any one suggest me how to get through it.
Here is my code:
const run = async () => {
let pairData = {
pair: {
asset_infos: [
{
token: {
contract_addr: "terra1s5eczhe0h0jutf46re52x5z4r03c8hupacxmdr",
},
},
{
native_token: {
denom: "uusd",
},
},
],
},
};
const pair = await terra.wasm.contractQuery(
"terra1s5eczhe0h0jutf46re52x5z4r03c8hupacxmdr",
Buffer.from(JSON.stringify(pairData)).toString("base64")
);
console.log(pair);
};
run();
With this code, this error is occurred.
Error: Request failed with status code 500
You don't need to convert to base64, provide the message as JSON and the sdk will automatically convert it for you.
At the moment, #terra-money/terra.js package version is > "^2.0".
And building the query json got easy.
You just need to insert ordinary JSON object as the parameter.
So, in your case, you just need to insert pairData, no need any Buffer or JSON.stringify conversions.
I'm doing a basic 'Visitor Book' function.
Users can submit a little form (with three inputs : name, msg and emoji).
I grab it with req.body in my router component. I'm using nodejs, with express and bodyparser.
I only want to store this data in a JSON, don't want any database involved here.
I'm in trouble with the writeFile method, using 'fs' module.
It work but it push the new data outside the single-array of my JSON file.
Do you know if I can push in inside the array ? Like a .push method, but with writeFile/appendFile/wathever that works good with json files.
Here is my code :
app.post (router) :
app.post('/visitorBook', async (req, res) => {
let formData = {
name: req.body.name,
msg: req.body.msg,
emoji: req.body.emoji
}
try {
console.log(req.body)
let data = JSON.stringify(formData, null, 2);
fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file
flag:'a' // this flag specify 'please append it' over 'please override file'
}
}, (err) => {
console.log('error :', err)
});
res.redirect('/contact')
} catch (error) {
console.error('/visitorBook route error : ', error)
}
})
My JSON :
[
{
"name": "test1",
"msg": "test1",
"emoji": "<i class='fas fa-hippo fa-3x'></i>"
},
{
"name": "test2",
"msg": "test2",
"emoji": "<i class='fas fa-hippo fa-3x'></i>"
}
]
{
"name": "sd",
"msg": "sd",
"emoji": "<i class='fas fa-kiwi-bird fa-3x'></i>"
}
So the last one with "sd" in name and msg is the pushed one. The 2 other are manually written by me, for readFile tests.
I hope I provided all the information needed. Not used to post here...
Thanks you.
If you read from the existing file and parse it with JSON.parse, you will be able to actually use Array.push on it. And then you can write the stringified result back into the file:
fs.readFile("./views/scripts/dataVisitorBook.json", function (err, data) {
if (err) throw err;
let data = JSON.parse(data.toString('utf8'));
data = JSON.stringify(data, null, 2);
fs.writeFile("./views/scripts/dataVisitorBook.json", data, { { // dataVisitorBook.json is the storage file
flag:'a' // this flag specify 'please append it' over 'please override file'
}
}, (err) => {
console.log('error :', err)
});
})
It might not be optimal though as it is likely to take more time as the file grows bigger.
I appreciate your simple try But using some standards can be much better to you
There are some Standard JSON DBs for Node like :
Simple JSON DB
Node JSON DB
Also, you can try SQLite
I also try with a simple JSON file of use as DB. I faced lots of work and I have managed it too. So my advice is to use some standard libraries
Apart from it, you have to get the file data Parse it as JSON (Decoding) make changes and again serialize it and write into a file (Encoding).
[SOLVED]
Thanks to #Divarrek , I've archieved to make it work.
So :
Read the file with fs.readFileSync.
Then, I store this rawdata in a variable, while parsing it to JSON.
THen, I push it in the 'jsonBook' variable which is the json file temporarly made into a simple object-variable.
Then I write in the file with writeFile, passing the data as variable 'parsed', which contain a JSON.stringified version of my 'jsonBook'
app.post("/visitorBook", async (req, res) => {
let formData = {
name: req.body.name,
msg: req.body.msg,
emoji: req.body.emoji,
};
try {
let rawdata = fs.readFileSync("./views/scripts/dataVisitorBook.json");
var jsonBook = JSON.parse(rawdata);
let formDataParsed = JSON.stringify(formData, null, 2);
jsonBook.push(formData);
let parsed = JSON.stringify(jsonBook, null, 2);
fs.writeFile("./views/scripts/dataVisitorBook.json", parsed, (err) => {
if (err) throw err;
console.log("saved");
});
res.redirect("/contact");
} catch (error) {
console.error("/visitorBook route error : ", error);
}
});
I hope I was clear. Maybe I did some explanation error, I'm trying my best.
Im tring to read a simple setting from a json file, the json is this :
{
"Label": "some string here"
}
form my javascript part i do:
import settings from '../settings.json';
then:
var settings= ()=> {
const headers = new Headers();
const requestOptions = {
method: 'GET',
headers: { ...headers.authentication, ...headers.culture, 'ContentType':'application/json',
};
return fetch(`${settings.Label}`, requestOptions).then(() => {
return response.text().then(text => {
const data = text ? text && JSON.parse(text) : {};
let token = response.headers.get('X-Token');
if (token) {
data.token = token;
}
if (!response.ok) {
// manage error here
}
return Promise.reject(error);
}
return data;
})
});
};
// use settings here
Despite my many searches and attempts im not very expert in javascript,i have tried in many ways before, but the my variable 'settings' is not contain nothing.
I believe you need to add an export to your JSON file
export const settings = {
"label": "some string here"
}
Not much information given here, but this probably has to do with transpiling your javascript. You can use:
const settings = require('../settings.json')
instead.
try this answer https://stackoverflow.com/a/59844868/7701381
Also, change the name of the imported json settings or the var settings, cuz this might cause unexpected behaviors
I had completely wrong the approach, the file is already available and I don't have to request to download it from the server, I just have to return string, without use of fetch or other:
return (`${settings.Label}`
Sorry and thank a lot for the support
I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin
According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)
The problem may be with the actual client, but he's not responding on github, so I'll give this a shot!
I'm trying to post, in the body, nested JSON:
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"{\"date\":\"2011-06-21T00:53:10.309Z\",\"disk0\":{\"kbt\":31.55,\"tps\":6,\"mbs\":0.17},\"cpu\":{\"us\":5,\"sy\":4,\"id\":90},\"load_average\":{\"m1\":0.85,\"m5\":0.86,\"m15\":0.78}}",
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
When I remove the columnvalue's json string, the POST works. Maybe there's something I'm missing regarding escaping? I've tried a few built in escape utilities to no avail.
var jsonString='the json string above here';
var sys = require('sys'),
rest = require('fermata'), // https://github.com/andyet/fermata
stack = require('long-stack-traces');
var token = ''; // Username
var accountId = ''; // Password
var api = rest.api({
url : 'http://url/v0.1/',
user : token,
password : accountId
});
var postParams = {
body: jsonString
};
(api(postParams)).post(function (error, result) {
if (error)
sys.puts(error);
sys.puts(result);
});
The API I'm posting to can't deserialize this.
{
"rowkeys":[
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":{
"date":"2011-06-21T00:53:10.309Z",
"disk0":{
"kbt":31.55,
"tps":6,
"mbs":0.17
},
"cpu":{
"us":5,
"sy":4,
"id":90
},
"load_average":{
"m1":0.85,
"m5":0.86,
"m15":0.78
}
},
"ttl":10000
},
{
"columnname":"cn",
"columnvalue":"cv",
"ttl":10000
}
]
},
{
"rowkey":"rk",
"columns":[
{
"columnname":"cn",
"columnvalue":"fd"
},
{
"columnname":"cn",
"columnvalue":"cv"
}
]
}
]
}
Dual problems occuring at the same occurred led me to find an issue with the fermata library handling large JSON posts. The JSON above is just fine!
I think the real problem here is that you are trying to post data via a URL parameter instead of via the request body.
You are using Fermata like this:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path(data).post(callback);
What path(data) represents is still a URL, with data showing up in the query part. So your code is posting to "http://example.com/path/endpoint?key1=value1&key2=value2" with an empty body.
Since your data is large, I'm not surprised if your web server would look at such a long URL and send back a 400 instead. Assuming your API can also handle JSON data in the POST body, a better way to send a large amount of data would be to use Fermata like this instead:
path = fermata.api({url:"http://example.com/path");
data = {key1:"value1", key2:"value2"};
path.post(data, callback);
This will post your data as a JSON string to "http://example.com/path" and you would be a lot less likely to run into data size problems.
Hope this helps! The "magic" of Fermata is that unless you pass a callback function, you are getting local URL representations, instead of calling HTTP functions on them.