invaild function while using express.js - javascript

invaild function while using express.js
in my app.js where express is installed some of the functions are not working
app.get("/",(req,res)=>{
const options = {
"method": "GET",
"hostname": "alexnormand-dino-ipsum.p.rapidapi.com",
"port": null,
"path": "/?paragraphs=1&words=1&format=json",
"headers": {
"x-rapidapi-key": "dcc30b2b2fmshac3b7e241a8fc6cp1061bdjsn8937e7e638cb",
"x-rapidapi-host": "alexnormand-dino-ipsum.p.rapidapi.com",
"useQueryString": true
}
};
https.get(options, function (response) {
response.on("data",function(data){
const dinoData = JSON.parse(data);
const b = dinoData.replace('[', '')
console.log(b);
})
})
res.render("main");
})
emphasized text
enter image description here

dinoData.replace('[', '') is incorect because of dinoData is not a string but object

This is because you are doing a replace on an object (here - dinoData.replace('[', '')), you would either have to iterate over the keys like below and check the values, or also check the keys etc. Or you could maybe remove the data you dont want before parsing the string to an object, but I would recommend the former and not the latter as you may corrupt the JSON.
const myJson = JSON.parse('*valid-json-goes-here*')
for (const key in myJson) {
// Might not be what you want, just an example
myJson[key] = myJson[key].replace('[', '')
}

Related

JSON Parse nested objects in React

I'm fetching data in React from a MySQL database. MySQL auto-escapes my values including nested objects. I'm using the .json() function on the top-level but i'm not able to use this on sub-levels, nor JSON.parse(response[0].data) will work.
What is the right way of doing this?
fetch(`http://localhost:3000/getQuiz${window.location.pathname}`, requestOptions)
.then(response => response.json())
.then(response => {
console.log(response)
// {
// "id": 1,
// "url": "asd2q13",
// "data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
// }
console.log(typeof response)
// object
console.log(response[0].data)
// {name: "Marie", answers:["1", "3", "0"]}
console.log(typeof response[0].data)
// string
console.log(response[0].data.name)
// undefined
})
The response.data is not a valid JSON string. You can try:
const response = {
"id": 1,
"url": "asd2q13",
"data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
}
console.log(eval('(' + response.data + ')'))
Or Better:
const response = {
"id": 1,
"url": "asd2q13",
"data": "{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}"
}
function looseJsonParse(obj) {
return Function('"use strict";return (' + obj + ')')();
}
console.log(looseJsonParse(response.data))
But,
Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.
I suggest you serialize the data correctly on the backend. I think the MySQL database driver can do this. Also, see Parsing JSON (converting strings to JavaScript objects)
MySQL (MySQL2) for Node was the big problem here. It's suppose to serialize "automatically", but somehow it ends up all wrong.
If I do JSON.Stringify() explicitly for the nested part before storeing it in the database it works!
const sendToDatabase = () => {
let nested = JSON.stringify({ name: "Marie", answers: ["2", "1", "0"] })
let post = { url: "asd2q13", data: nested}
var query = connection.query(
"INSERT INTO users SET ? ", post,
function (error, results, fields) {
if (error) throw error;
}
);
console.log(query.sql);
};
Then I call this on the front end
console.log(JSON.parse(response[0].data).name)
// Marie (string)
console.log(JSON.parse(response[0].data).answers)
// ["2", "1", "0"] (array)
The raw output from this is
{"name":"Marie","answers":["2","1","0"]}
insted of
{name: \"Marie\", answers:[\"1\", \"3\", \"0\"]}

How to parse json in react native

I'm working on react native project, and i'm calling API and extracting data from it , the data is succesfully extracted but I want to take arguments from the extracted data and I did'nt know how
This is the code for fetching api :
Axios({
url: '/Authentification',
method: 'get',
baseURL: 'http://smart.netrostercloud.com/api',
transformRequest: [
function (data, headers) {
return data;
},
],
transformResponse: [
function (data) {
// console.log(data);
setData3(data);
},
],
headers: {
Authorization: 'Basic UxvwJc1GWjkOCyZoIHGuCD05gDUB72sqrgK30FgILho=',
},
});
console.log(data3);
I've used data3 to extract the data in my main function so it can be visible.
This is the data :
I want to take CompanyCode,UserName,Password,FirstName and LastName
Firstly : axios its n asynchronous function, so its return a promise,
Actually i dont prefere use this patern in simple api call l, but its good way if you know this concept and use oop like create instance of axios to reusable and cancel connectiin when component will unmount.
Fot this i prefere use this way
Const getUserData= async () =>{
try {
Const {data} = await axios.get(baseurl+route, headers , options)
data & & SetData({username:data. User. Username,........... } )
Dosomthing...
}
Catch(error) {
Dosomthing...
}
Before you storing data into data3 you need to stringify the data like this setData3(JSON.stringify(data));
and then try this:
if (data3) {
const COMP_NAME = data?.user?.CompanyCode;
const USER_NAME = data?.user?.UserName;
CONST FIRST_NAME = data?.user?.FirstName;
CONST LAST_NAME = data?.user?.LastName;
}

Extra semicolon showing up in axios get request

I am trying to dynamically build an axios get request, and have currently hardcoded some values in my parameters array to test with like so:
const parameters = [
'table=cumulative',
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
'order=koi_period',
'format=json'
];
let searchParameters = '';
const api = axios.create({
baseURL: 'https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI'
});
for (let element in parameters) {
if (element !== '') {
searchParameters += `?${parameters[element]}`;
}
}
I then add this query to my axios get request below:
export const getExoplanets = async () => {
try {
searchParameters = searchParameters.replace(/;/g, "");
console.log(`${searchParameters}`);
return await api.get(`${searchParameters}`);
// return await api.get(`?table=cumulative&where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2&order=koi_period&format=json`);
} catch (error) {
return error;
}
};
When the variable version runs the api returns the error:
ERROR
Error Type: UserError
Message: Constraint contains an illegal keyword: ";"
However when the commented out, hard coded version runs it works just fine. At some point an extra semicolon is being added to the request. I assume it is being added at the end, but I can't find where or how. Any ideas how to fix this?
Axios supports easy query parameters using the params config option.
Just provide an object of key / value pairs and Axios will do all the encoding for you
const params = {
table: "cumulative",
where: "koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",
order: "koi_period",
format: "json"
}
return api.get("", { params })
// or return api.get("", { params: params })
This will send a request to
?table=cumulative&where=koi_disposition+like+%27CANDIDATE%27+and+koi_period%3E300+and+koi_prad%3C2&order=koi_period&format=json
it seem you having an issue in this bellow line you have used the \ rest of this you can wrap all the things in the double quote.
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
"where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",

JavaScript - Url encoding of Array type parameters

I can't figure out how to URL encode array params in an elegant way, in order to send XHR requests from my Vue.js client to my Symfony PHP API.
For example i have this GET method endpoint:
/question/list?subjects={idSubject}
It lists Question entity items and optionally, accepts params in order to filter results by them (subjects in this case)
The desired one would be:
/question/list?subjects[]={idSubject}&subjects[]={idSubject}
I'm using Axios for Vue.js to perform XHR requests and i created a main class that implements the methods that i want.
As the get() method doesn't support 'data' property in config object, i implemented it at the same way of a POST call and then i process it in order to build the desired URL.
This is my Ajax.js file:
const ajaxRequest = (config) => {
const token = TokenStorage.get()
config.baseURL = '/ajax'
if (token) {
config.headers = {
'Authorization': 'Bearer ' + token
}
}
return Axios.request(config)
}
const Ajax = {
get: (endpoint, params = null, config = {}) => {
const querystring = require('querystring')
let url = endpoint
if (Array.isArray(params) && params.length) {
url += '?' + params.join('&')
} else if (typeof params === 'object' && params !== null && Object.keys(params).length) {
url += '?' + querystring.stringify(params)
}
config = {
...config,
...{
url: url,
method: 'get'
}
}
return ajaxRequest(config)
},
post: (endpoint, params, config = {}) => {
config = {
...config,
...{
url: endpoint,
method: 'post',
data: params
}
}
return ajaxRequest(config)
}
}
I know that I could pass this data by POST but, in order to follow restful design, i want to keep GET method and optional params can be included in the URL as GET params.
If it were me I'd build a JavaScript array then call JSON.stringify() on it... then URL encode the resultant string and attach it as the sole parameter... to be JSON parsed by your server side handler.
I'm in a similar situation and I couln't find a built in library for this.
the most elegant solution I've found so far is by adding
Array.prototype.encodeURI = function(name) {
prefix = `${name}[]=`;
return prefix + this.map(o => encodeURI(o)).join(`&${prefix}`);
}
now you can use it:
let subjects = ["First Subject", "Second Subject"];
let myquery = subjects.encodeURI("subjects")
console.log(myquery)
// 'subjects[]=First%20Subject&subjects[]=Second%20Subject'
Note:
For empty arrays (e,g: let arr = [];) this method responds with subjects[]=, which php reads as an array with a single empty string (e,g: print_r($_REQUEST["subjects"]) prints Array ( [0] => )).
I couldn't find a standard for sending empty arrays url encoded and you should handle that somewhere.

How to Filter JSON.parse results

I have been trying to filter the results of an API call based on my "note" value. I've been building it on Zapier and the call works but I cannot seem to find a way to make a filter function do its job (so if I replace line 19-23 with return results; then it gives me all orders from the api call). I've poured over every stack document I could find but they all end with the error result.filter not found, or a bargle error (generic error in Zapier).
const options = {
url: `https://mystorename.myshopify.com/admin/orders.json?`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
var results = z.JSON.parse(response.content);
var queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem);
return filteredOrders;
});
And this is an example of my current output with return results; and no filter:
{
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
Again the goal is to filter by the value in the "note" key. So if my filter input is 555-5555 then it should return all information for that item only. I did try to use an if statement for return, stringify instead of parse, covert to array...all with needed code, but regardless of the format I find filter does not work or nothing is returned. Going to keep working on it, so if I happen to find the answer I will post that, but at this point I feel stuck.
You are trying to use the method filter in a object but filter is only available in an array so you should try to call filter in the orders array.
let results = {
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
let queryItem = "555-5555";
let newArray = results.orders.filter(function (item) {
return item.note == queryItem
})
console.log(newArray)
Updated to contain a real http call:
const url = 'http://www.mocky.io/v2/5d9466142f000058008ff6b7'
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
const response = await fetch(url, options)
const results = await response.json()
const queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem)
console.log(filteredOrders)
You are trying to filter on results, but according to your output, you should be filtering on results.orders.
const filteredOrders = results.orders.filter(item => item.note === queryItem);
Are you getting all the orders back (all the orders with the specified filter value)?
I realized I wasn't getting back all orders and this did the trick:
`https://mystorename.myshopify.com/admin/orders.json?status=any`
Alternatively, you can query the orders with that specific note:
`https://mystorename.myshopify.com/admin/orders.json?status=any&note=` + queryItem

Categories