axios is not getting response - node.js

const getReq = async () => {
try {
const res = await axios.get('https://www.peoplestuffuk.com/WFMMCDPRD/LoginSubmit.jsp?txtUserID={user}&txtPassword={password}')
console.log(res)
} catch (e) {
console.log(e.message)
}
}
I am getting 'Request failed with status code 500' whereas it's getting response on puppeteer and postman.I can't get around this! Is it because the site is large or slow.Any help will be very appreciated demo on postman

Try to replace your
const res = await axios.get('https://www.peoplestuffuk.com/WFMMCDPRD/LoginSubmit.jsp?txtUserID={user}&txtPassword={password}')
with
const res = await axios.get(`https://www.peoplestuffuk.com/WFMMCDPRD/LoginSubmit.jsp?txtUserID=${user}&txtPassword=${password}`)
Looks like you're passing your variables as a part of the string

Related

Uncaught (in promise) TypeError: "nameMyFunction" is not a function in useEffect React

I'm sorry for my English. I'm using a translator. I have the following problem. I'm trying to use a function from another component, but it gives me the following error.
I will leave the code extract:enter image description here
I used useEffect to display the data for an id depending if that id has records:
export async function getOrderByTableApi(idTable, status= "", ordering= ""){
try {
const tableFilter = `table=${idTable}`;
const statusFilter = `status=${status}`;
const closeFilter = "close=false";
const url = `${BASE_API}/api/orders/?${tableFilter}&${statusFilter}&${closeFilter}&${ordering}`;
const response = await fetch(url);
const result = await response.json();
return result;
} catch (error) {
throw error;
}
}
the function comes from another component as follows:
import { getOrderByTableApi } from "../api/orders";
export function useOrder(){
const [setLoading] = useState(true);
const [setError] = useState(false);
const [setOrders] = useState(null);
const getOrderByTable = async (idTable, status, ordering) => {
try {
setLoading(true);
const response = await getOrderByTableApi(idTable, status, ordering);
setLoading(false);
setOrders(response);
} catch (error) {
setLoading(false);
setError(error);
}
};
return{
getOrderByTable,
};
}
and when using it, the console tells me that getOrderByTable is not a function
import { useTables } from "../../hooks";
export function OrdersHistory() {
const [idTable, setIdTable] = useState(null);
const { getOrdersByTable } = useOrder();
const { getTableByNumber } = useTables();
useEffect(() => {
(async () => {
const table = await getTableByNumber(tableNumber);
const idTableTemp = table[0].id;
setIdTable(idTableTemp);
**getOrdersByTable(idTableTemp, "", "ordering=-status,-created_at");**
})();
}, []);
return (
<p>Help please</p>
);
}
adjunto imagen
There is a typing mistake in your code. You're exporting the function as getOrderByTable from your custom hook useOrder but you're importing it as getOrdersByTable instead of getOrderByTable in your OrdersHistory component.
If you want to rename your function, you can do it as below
const { getOrderByTable as getOrdersByTable } = useOrder();
I appreciate the review, due to fatigue I did not notice that the name of the function did not match a letter and that is why it gave me an error, I will take the recommendation to copy and paste the names of the functions in the future, I consider this question closed. Thank you so much.

Web3 getPastEvents Returned error: limit exceeded

I am using web3 function getPastEvents and I am getting error:
Returned error: limit exceeded
I also changed RPC url but same error occured their.
Is there any other way to get event data ?
this is my code:
const http = require("http");
const cron = require('node-cron');
const { randomBytes } = require("crypto");
const web3 = new Web3("https://bsc-dataseed.binance.org/");
//console.log("Hello This",web3);
//console.log("hello");
const dexABI =contractAbi;
const contract_address = "0xd19EA9d72828444BC7bAE231fBa66F8050e72b1b";
const contract = new web3.eth.Contract(dexABI, contract_address);
async function generateEventQuery(result) {
console.log(result);
return ;
}
http
.createServer((req, res) => {
web3.eth
.getBlockNumber()
.then((d) => {
let current_block = d;
console.log(current_block);
contract
.getPastEvents({
fromBlock: Number(23390147),
toBlock: Number(23390147)+100,
})
.then( async(events) => {
let resu = await generateEventQuery(events);
})
.catch((e) => {
console.log("Err",e)
res.write("Err:" + JSON.stringify(e));
res.end();
});
})
.catch((e) => e);
})
.listen(8080);
in the function getPastEvents() you have to take the first parameter as your event name which you want to fetch the data. The name should be as same as in your contract and passed into a string.
Actually, this is an RPC problem. I replaced https://bsc-dataseed.binance.org/ with https://bscrpc.com. Now it works properly.
Public RPC URLs like https://bsc-dataseed.binance.org/ or https://bscrpc.com have rate-limiting to prevent people from over using it.
It's fine for testing but in production you should use your own node or a blockchain API like Infura, Alchemy, QuickNode or any other.

Axios returning undefined when trying to obtain an image link

So, I have this simple axios script which is supposed to get bitcoin's image using the coingecko API.
const axios = require("axios");
async function test() {
const { data } = await axios.get(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin&order=market_cap_desc&per_page=100&page=1&sparkline=false`
);
console.log(data.image);
}
test();
Although, when I run it, it just returns undefined.
Whenever I try to print data, it returns this:
What am I doing wrong?
You are getting data as an array not an object
Inside data it is at 0th index.you check inside data[0] and not inside data.
So answer will be data[0].image
const axios = require("axios");
async function test() {
const { data } = await axios.get(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin&order=market_cap_desc&per_page=100&page=1&sparkline=false`
);
console.log(data[0].image);
}
test();

List request not working (Mongoose in Node.js with Typescript)

I am using mongoose in Nodejs with typescript. In a list request, I have the following code:
async list(req: Request, res: Response, next: NextFunction)
{
try {
let list: ListInterface[] = []
await RequestModel.find().then(requests =>
{
requests.map(async request =>
{
const client = await Client.findById(request.cliente)
const seller = await Seller.findById(request.vendedor)
const company = await Company.findById(request.representada)
const tmp =
{
id: request._id,
data: request.data,
cliente: String(client?.nome_fantasia),
vendedor: String(seller?.nome),
representada: String(company?.nome_fantasia),
tipo: request.tipo,
status: request.status
}
list.push(tmp)
console.log(tmp)
})
})
console.log(list)
return res.json(list)
} catch (error) {
next(error)
}
}
When I make the request in Insomnia, I receive an empty array (both in the terminal -- because of console.log(list) -- and on Insomnia's preview): []. In the terminal, as a result of the console.log(tmp) command, I receive the proper data.
I have already tried to declare the list as something like const list = request.map(...), but it gives me [Promise<Pending>, Promise<Pending>] in the terminal and [{}, {}] in Insomnia. I could not repeat exactly the same code of this test, but I remember those results.
I'm not even sure about which technology I'm misusing. Could someone please help me with this problem?
.map function returns a list of promises, so have to wait for them before sending back the response.
async list(req: Request, res: Response, next: NextFunction)
{
try {
let list: ListInterface[] = []
const requests = await RequestModel.find()
// collect all promises from the loop
const promises = requests.map(async request =>
{
const client = await Client.findById(request.cliente)
const seller = await Seller.findById(request.vendedor)
const company = await Company.findById(request.representada)
const tmp =
{
id: request._id,
data: request.data,
cliente: String(client?.nome_fantasia),
vendedor: String(seller?.nome),
representada: String(company?.nome_fantasia),
tipo: request.tipo,
status: request.status
}
list.push(tmp)
console.log(tmp)
})
// wait for all promises to complete
await Promise.all(promises)
console.log(list)
return res.json(list)
} catch (error) {
next(error)
}
}

Pass query from Link to server, first time load query value undefined, after reload get correct query

I try to create some API to external adobe stock.
Like in the title, first time i get query from Link router of undefined, but after reload page it work correctly. My
main page
<Link
href={{
pathname: "/kategoria-zdjec",
query: images.zdjecia_kategoria
}}
as={`/kategoria-zdjec?temat=${images.zdjecia_kategoria}`}
className={classes.button}>
</Link>
and my server
app
.prepare()
.then(() => {
server.get("/kategoria-zdjec", async (req, res) => {
const temat = await req.query.temat;
console.log(temat)
const url = `https://stock.adobe.io/Rest/Media/1/Search/Files?locale=pl_PL&search_parameters[words]=${temat}&search_parameters[limit]=24&search_parameters[offset]=1`;
try {
const fetchData = await fetch(url, {
headers: { ... }
});
const objectAdobeStock = await fetchData.json();
res.json(objectAdobeStock);
const totalObj = await objectAdobeStock.nb_results;
const adobeImages = await objectAdobeStock.files;
} catch (error) {
console.log(error);
}
});
and that looks like getInitialProps on page next page
Zdjecia.getInitialProps = async ({req}) => {
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
I think it is problem due asynchronous.
I think this might be due to the fact that you are using fetch which is actually part of the Web API and this action fails when executed on server.
You could either use isomorphic-fetch which keeps fetch API consistent between client and server, or use node-fetch when fetch is called on the server:
Zdjecia.getInitialProps = async ({ req, isServer }) => {
const fetch = isServer ? require('node-fetch') : window.fetch;
const res = await fetch("/kategoria-zdjec");
const json = await res.json();
return { total: json.nb_results, images: json.files };
}
This problem is solved, the issue was in another part of my app, directly in state management, just created new variables, and pass to link state value.

Resources