filter query param not working through axios get from my vue js application? - vue.js

whenever a user types anything into the textfield, an axios get request to the url
http://sandbox4.wootz.io:8080/api/data/1/action/?filter={id}like'%TE%' is made and it is supposed to return back all the filtered results based on the search(what user has typed) as a response. But currently rather than returning the filtered results as a response it is giving out all results(non-filtered results).
NOTE: I have tested the above mentioned URL through postman by making a get request and it gave out the filtered results perfectly.Why is the same not happening through my application code?plz help
getAsyncDataAction: debounce(function(name) {
if (!name.length) {
this.dataAction = [];
return;
}
this.isFetching = true;
api
.getSearchData(this.sessionData.key,`/action/?filter={id}like'%${name}%'`)
.then(response => {
this.dataAction = [];
response.forEach(item => {
this.dataAction.push(item);
});
console.log('action results are'+JSON.stringify(this.dataAction)) //displays all the results(non-filtered)
})
.catch(error => {
this.dataAction = [];
throw error;
})
.finally(() => {
this.isFetching = false;
});
}, 500),
api.js
import axios from 'axios';
const props = {
base_url: '/api/store',
search_url: '/api/entity/search',
cors_url: 'http://localhost',
oper_url: '/api'
};
axios.defaults.headers.get['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.patch['Access-Control-Allow-Origin'] = props.cors_url;
async function getSearchData(key, path) {
try {
console.log('inside getSearchData path value is'+path)
console.log('inside getSearchData and url for axios get is '+props.base_url + '/data' + path)
let response = await axios({
method: 'get',
url: props.base_url + '/data' + path,
headers: {'session_id': key}
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}

The problem is that you're not encoding the query string correctly. In particular, your % signs need to become %25
To do this, I highly recommend using the params options in Axios.
For example
async function getSearchData(key, path, params) { // 👈 added "params"
// snip
let response = await axios({
method: 'get',
url: `${props.base_url}/data${path}`,
params, // 👈 use "params" here
headers: {'session_id': key}
});
and call your function with
const params = {}
// check for empty or blank "name"
if (name.trim().length > 0) {
params.filter = `{id}like'%${name}%'`
}
api
.getSearchData(this.sessionData.key, '/action/', params)
Alternatively, encode the query parameter manually
const filter = encodeURIComponent(`{id}like'%${name}%'`)
const path = `/action/?filter=${filter}`
Which should produce something like
/action/?filter=%7Bid%7Dlike'%25TE%25'

Related

Struggling to correctly make use of returned values from functions that are being called Asynchronously by Axios

I have an Express server which serves as an API Request forwarding tool (i.e my client calls the express server, and the express server forwards that call to another API).
The way this server is supposed to work is that there is a single entry point which makes a request, and then based on the response makes further API requests and returns a result based on the combo of API request responses.
To be clearer, the main logic is as follows:
Single entry point, which makes an async axios call to get an ID value
Within this function, we call an async function, getPartnerDetails (passing that ID as the parameter)
getPartnerDetailscalls a 3rd async function, '''getRawJson''' which is supposed to return the final required result, passing it back to '''getPartnerDetails''' which then passes it to the main entry point.
Whats going wrong is that the results are being recieved but are not being pass back correctly. The console logs within the '''.then(()=>{})''' of my async functions are coming back as '''undefined'''.
Code below:
app.post('/checkuser', async (req, res, next) => {
const { man, bfn, bln, bsn, bc, bs, bz, bco } = req.body;
const bodyContent = {
man: man,
bfn: bfn,
bln: bln,
bsn: bsn,
bc: bc,
bs: bs,
bz: bz,
bco: bco,
profile: 'DEFAULT',
};
try {
await axios
.post('https://host.com/im/account/consumer', bodyContent, { headers })
.then((response) => {
const addressValidResult = response.data.score.etr.filter(
(result) => result.test === '19:2'
)[0];
// console.log(res.json(result.details));
const requestId = response.data.mtid;
const currentValidAddress = getPartnerDetails(requestId).then(
(result) => {
console.log('this is currentvalidaddress ' + result);
res.json({
validationMessage: addressValidResult,
currentValidAddress: result,
});
}
);
})
.catch((err) => next(err));
} catch {}
});
async function getPartnerDetails(appId) {
let config = {
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic M2QzMsdfsslkfglkdjfglkdjflkgd',
},
params: {
partner: 19,
},
};
const res = await axios
.get(
`https://host.com/im/account/consumer/${appId}/partner/requests`,
config
)
.then((response) => {
const requestId = response.data.requests[0].request_id;
console.log('this is request id ' + JSON.stringify(requestId));
const raw = getRawJson(appId, requestId).then((result) => {
console.log('this is getRawJson result ' + JSON.stringify(result));
return JSON.stringify(result);
});
// https://host.com/im/account/consumer/:appId/partner/request/:requestId
})
.catch((err) => console.log('err2' + err));
}
async function getRawJson(appId, requestId) {
const res = await axios
.get(`host.com/im/account/consumer/${appId}/partner/request/${requestId}`, {
headers,
})
.then((response) => {
console.log('this is response ' + JSON.stringify(response.data));
return JSON.stringify(response.data);
})
.catch((err) => console.log('err1 ' + err));
}
It might have something to do with how I'm using async and await, I'm new to it so I'm hoping that I'll learn a thing or 2 more about it by solving this project.
I'm also aware that maybe I should split the entry point out into 3 different entry points, and have the client manage the chaining of the requests and responses instead.
Thanks!!
Probably an error due to incorrect async await usage.
Try to change your code like this:
app.post('/checkuser', async (req, res, next) => {
const { man, bfn, bln, bsn, bc, bs, bz, bco } = req.body;
const bodyContent = {
man: man,
bfn: bfn,
bln: bln,
bsn: bsn,
bc: bc,
bs: bs,
bz: bz,
bco: bco,
profile: 'DEFAULT',
};
try {
const { data } = await axios.post(
'https://host.com/im/account/consumer',
bodyContent,
{ headers }
);
const addressValidResult = data.score.etr.filter(
(result) => result.test === '19:2'
)[0];
const requestId = data.mtid;
const currentValidAddress = await getPartnerDetails(requestId);
console.log('this is currentvalidaddress ' + currentValidAddress);
res.json({
validationMessage: addressValidResult,
currentValidAddress: currentValidAddress,
});
} catch (err) {
next(err);
}
});
async function getPartnerDetails(appId) {
let config = {
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic M2QzMsdfsslkfglkdjfglkdjflkgd',
},
params: {
partner: 19,
},
};
const { data } = await axios.get(
`https://host.com/im/account/consumer/${appId}/partner/requests`,
config
);
const requestId = data.requests[0].request_id;
console.log('this is request id ' + JSON.stringify(requestId));
return getRawJson(appId, requestId);
}
function getRawJson(appId, requestId) {
return axios
.get(`host.com/im/account/consumer/${appId}/partner/request/${requestId}`, {
headers,
})
}

RN "TypeError: Network request failed" - production - random

I know some questions about the subject has been opened here and there, but my issue is different :
all the other ones appear in dev mode, in my case it's in production,
a very big percentage of requests pass, a few of them is TypeError: Network request failed - but sometimes for critical requests
it's random, not always the same request. Sometimes it passes, sometimes not.
it appears to three on my projects, one is on AWS the other one on Clever-Cloud, both are projects between 1000 and 5000 users, servers are quite too big for what they do - I think I removed the risk of a server fault. Even if... I can reproduce locally when I don't start the api locally. So it's like the api is not responding, but as I said, I don't think so.
I have no clue where to dig anymore...
I can give you my API.js service file, maybe you'll find what's wrong ?
import URI from 'urijs';
import { Platform } from 'react-native';
import NetInfo from '#react-native-community/netinfo';
import { getUserToken, wipeData } from '../utils/data';
import { SCHEME, MW_API_HOST } from '../config';
import deviceInfoModule from 'react-native-device-info';
import { capture } from '../utils/sentry';
const unauthorisedHandler = (navigation) => {
wipeData();
navigation.reset({ index: 0, routes: [{ name: 'Auth' }] });
};
const checkNetwork = async (test = false) => {
const isConnected = await NetInfo.fetch().then((state) => state.isConnected);
if (!isConnected || test) {
await new Promise((res) => setTimeout(res, 1500));
return false;
}
return true;
};
class ApiService {
host = MW_API_HOST;
scheme = SCHEME;
getUrl = (path, query) => {
return new URI().host(this.host).scheme(this.scheme).path(path).setSearch(query).toString();
};
execute = async ({ method = 'GET', path = '', query = {}, headers = {}, body = null }) => {
try {
const config = {
method,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
appversion: deviceInfoModule.getBuildNumber(),
appdevice: Platform.OS,
currentroute: this.navigation?.getCurrentRoute?.()?.name,
...headers,
},
body: body ? JSON.stringify(body) : null,
};
const url = this.getUrl(path, query);
console.log('url: ', url);
const canFetch = await checkNetwork();
if (!canFetch) return;
let response;
// To try to avoid mysterious `TypeError: Network request failed` error
// that throws an error directly
// we try catch and try one more time.
try {
response = await fetch(url, config);
} catch (e) {
if (e?.toString().includes('Network request failed')) {
// try again
await new Promise((res) => setTimeout(res, 250));
console.log('try again because Network request failed');
response = await fetch(url, config);
} else {
throw e;
}
}
if (!response.ok) {
if (response.status === 401) {
const token = await getUserToken();
if (token) unauthorisedHandler(API.navigation);
return response;
}
}
if (response.json) return await response.json();
return response;
} catch (e) {
capture(e, { extra: { method, path, query, headers, body } });
return { ok: false, error: "Sorry, an error occured, technical team has been warned." };
}
};
executeWithToken = async ({ method = 'GET', path = '', query = {}, headers = {}, body = null }) => {
const token = await getUserToken();
if (token) headers.Authorization = token;
return this.execute({ method, path, query, headers, body });
};
get = async (args) => this.executeWithToken({ method: 'GET', ...args });
post = async (args) => this.executeWithToken({ method: 'POST', ...args });
put = async (args) => this.executeWithToken({ method: 'PUT', ...args });
delete = async (args) => this.executeWithToken({ method: 'DELETE', ...args });
}
const API = new ApiService();
export default API;
Talking with experts here and there, it seems that it's normal : internet network is not 100% reliable, so sometimes, request fail, for a reason that we can't anticipate (tunnel, whatever).
I ended up using fetch-retry and I still have a few of those, but much less !

i am trying to fecth html page with react-native-html-parser

How to parse html page from fetch response?
I have checked both async and regular promise syntax but nothing seems to compile:
const fetch = require('node-fetch'); var DOMParser = require('react-native-html-parser').DOMParser;
function getbooks() {
fetch('https://github.github.io/fetch/').then(function(response) {
if (response) {
return response
} else {
var error = new Error(response.statusText)
error.response = response
throw error
}
})
}
const books=getbooks();
console.log(books);
var DOMParser = require('react-native-html-parser').DOMParser;
var doc = new DOMParser().parseFromString(
books);
console.log(doc);
console.log('end');
What gets returned from your endpoint?
You Can try:
NOTE: Your trying to log a response from something that is asyncrhonus. You need to use
async and await (with promises). Something like...
async function getBooks(){
var response = await fetch('https://github.github.io/fetch/', {
method: 'GET',
headers: {
Accept: 'application/json',
},
}).then((response) => {console.log(response);return response})
.then((responseJson) => {
return responseJson.json();
})
.catch((error) => {
console.error(error);
return {error: "Couldn't get books"}
});
console.log(response);
}
getBooks();

get item from asyncstorage in constructor and pass it to other method - react native

I have a file called Server.js in which I have written parent method to make get and post request. I am trying to extract few items from async-storage in the constructor and passing it to a method where I am assigning it to another variable. Now I have to use this variable inside my get and post method but unable to access the new variables(which are declared inside the constructor itself).
These new initialized variables are accessible by post method, but not inside the get method. When I tried some other workaround, it says that all my 3 variables ( participantId, mobeToken, urlAsync are undefined. Any input on my above issue.
variables :
1. participantId: will be sent as a header attribute (for authentication).
2. mobeToken: token for authentication, sent in Get request just like participantId.
3. urlAsync: its the url in which all the calls will be made. Once this is accessible inside Get and post method, I will remove this.baseUrl from both, Get & Post method request.
import React, { Component } from "react";
import { Alert,AsyncStorage} from 'react-native';
import axios from "axios";
const DEV_ENV_URL = "http://www.aaa.com/api";
const STAGE_ENV_URL = "http://www.bbb.com/api";
const PROD_ENV_URL = "http://www.ccc.com/api";
export default class Server extends Component {
baseUrl = DEV_ENV_URL;
constructor(props) {
super(props);
mobeToken1 = "";
participantId1 = "";
urlAsync = "";
AsyncStorage.getItem("profile", (err, res) => {
if (res !== null) {
let profile = JSON.parse(res);
participantId = profile.participantId;
} else {
profile = "";
}
AsyncStorage.getItem("mobeToken", (err, mobeToken) => {
AsyncStorage.getItem("URL", (err, Url) => {
this.assignValues(participantId, mobeToken, Url);
});
});
});
}
assignValues(participantId, mobeToken, Url) {
participantId1 = participantId;
mobeToken1 = mobeToken;
urlAsync = Url;
console.log("mobeToken1 "+ mobeToken1 + "," + participantId1 +"," + urlAsync);
}
getRequest(url) {
// debugger;
console.log(mobeToken1); // need variables in this method but can't
return fetch(this.baseUrl + url , {
method: 'GET',
headers: {
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch(error => {
console.log(error);
Alert.alert("", "Network connection issue. Please contact support");
});
}
postRequest(url, jsonData) {
return fetch(this.baseUrl + url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
// 'Content-Type': 'application/text',
"parse-array": "|entryJSONList|",
"mobeToken": mobeToken1,
"participantId": participantId1,
},
body: JSON.stringify(jsonData)
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
return responseJson;
})
.catch(error => {
console.log(error);
Alert.alert("", "Network connection issue. Please contact support");
});
}
}
Is there any alternative solution for this?
Thanks for viewing or providing solutions to this....

GraphCool TypeError: Converting circular structure to JSON

I copy-pasted example from official documentation in hope that I will see some different error (invalid URL or invalid auth key or something similar) However I get some webpack/sandbox error:
const fetch = require('isomorphic-fetch')
const Base64 = require('Base64')
const FormData =require('form-data')
const apiKey = '__MAILGUN_API_KEY__'
const url = '__MAILGUN_URL__'
export default event => {
const form = new FormData()
form.append('from', 'Nilan <nilan#graph.cool>')
form.append('to', 'Nikolas <nikolas#graph.cool>')
form.append('subject', 'Test')
form.append('text', 'Hi')
return fetch(url, {
headers: {
'Authorization': `Basic ${Base64.btoa(apiKey)}`
},
method: 'POST',
body: form
})
}
Even simple API requests fail:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
}
The code above also returns:
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at /data/sandbox/lib/sandbox.js:532:48
at /data/io/8e0059b3-daeb-4989-972f-e0d88e27d15e/webtask.js:46:33
at process._tickDomainCallback (node.js:481:9)
How do I successfully call API from custom graphcool subscription/resolver?
This is the simplest working example:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
return {
data: {
sum: 3
}
}
})
}