How fix the bounds problem with openrouteservice API - reactjs

I am trying send a request with openrouteservice, when I sent the coordinates I receive a error response
I am using react with the openrouteservice-js library
getResponse = async () => {
try {
const response = await Directions.calculate({
coordinates: [[9.930808,-84.052448],[9.933302,-84.056493]],
attributes: ['detourfactor'],
profile: 'driving-car',
extra_info: ['waytype', 'steepness'],
avoidables: ['highways', 'tollways', 'ferries', 'fords'],
instructions: true,
instructions_format: 'text',
preference: 'recommended',
units: 'km',
language: 'es',
format: 'json'
});
console.log(response);
this.setState({ response })
} catch (e) {
console.log(e, 'error');
}
}
Example map: https://maps.openrouteservice.org/directions?n1=9.933376&n2=-84.05461&n3=17&a=9.930808,-84.052448,9.933302,-84.056493&b=0&c=0&k1=en-US&k2=km
If I put the same coordinates in the example map the route is work fine, but when I sent the request I get this response error:
{
"error": {
"code": 2010,
"message": "Point 0 is out of bounds: -84.052448,9.930808"
}, "info": {
"engine": {
"version": "5.0.1",
"build_date": "2019-05-24T16:27:11Z",
},
"timestamp": 1558719789443
}
}

Not sure if this is still active, but I'll leave this answer here for others who might have this problem...
Many Geographical APIs accept [latitude, longitude] pairs, but Open Routes Service accepts [longitude, latitude]. If you swap them, the locations will snap to completely different locations, and if they happen to be in the ocean or outside of an inhabited area (mine was in Antarctica), this error message will be returned.
As the comment on the question said, though, it's also possible to get this error message through using the wrong map on your local version of the Open Routes Service.

Related

AxiosError when integrating Stripe with Next.js

I am relatively new to Next.js, and I though I have been encountering some bugs and issues here and there, I have been able to overcome most of them. The latest one I have not been able to figure out, so let's see if somebody else knows what's going on.
I am creating an e-commerce platform on Next.js, Redux and Axios. For the moment I am using fake data to populate the products. When creating a checkout session, the data of the items in the cart is pushed (I can console.log() and I see the items in the terminal. However, the mapping of the checkout session to Stripe is not working. The error I get is an AxiosError: Request failed with status code 500
Error message screenshot
I am trying to add the item data dynamically to the checkout session as follows:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
description: item.description,
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};
I have also tried copying the exact code from the Stripe documentation and implementing the changes, but this hasn't changed anything either.
I know, Stripe has made some changes to their API, and that for instance you can't specify anymore with statements like
payment_method_types: ["card"],
anymore. So I took it out.
I have not included any code from the checkout piece, as this seems to be working (as stated, it console.logs() just fine. I can provide this as well though, if someone thinks the issue might be there.
Thanks in advance.
Nela.
Thanks to Code-Apprentice and maiorano84 whose hints in the comments:
A status code 500 means there is an error on the backend. If the server is under your control, then you need to look at the server logs to see what the problem is. The server logs will have a stack trace that shows you where the problem occurs. If you need help understanding the stacktrace, you will need to include it in your question. – Code-Apprentice 22 hours ago
Is this a server-side or client-side AJAX request? If it's the latter, check your network tab to see the full output of your failed request (marked in red in Chrome Devtools). You should be able to get more information about the failed request there. If it's failing on the Stripe side, the Response Headers and Body should have more information there to help you debug. If it's failing on your own success and checkout callbacks, your server logs might have additional information that can help you. – maiorano84 22 hours ago
led me to the answer. I checked my console, and the error that was given was from Stripe. It read as follows:
StripeInvalidRequestError: You cannot use line_items.amount, line_items.currency, line_items.name, line_items.description, or line_items.images in this API version. Please use line_items.price or line_items.price_data.
So I moved the item.description I had outside of the product_data object, into it, and it worked.
The code looks now like this:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const { items, email } = req.body;
const transformedItems = items.map((item) => ({
// if quantities are bundled, this needs to change.
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: item.price * 100,
product_data: {
name: item.title,
description: item.description,
images: [item.image],
},
},
}));
const session = await stripe.checkout.sessions.create({
line_items: transformedItems,
mode: 'payment',
success_url: `${process.env.HOST}/success`,
cancel_url: `${process.env.HOST}/checkout`,
metadata: {
email,
images: JSON.stringify(items.map((item) => item.image)),
},
});
res.status(200).json({ id: session.id });
};

Adding a custom network to MetaMask with http address isn't working using wallet_addEthereumChain

I am creating a button that adds a custom network to MetaMask. The issue is the geth node has an http address not a https. When I run the code to add with wallet_addEthereumChain I get an error saying it expects an https address. Is there a way around this.
const formattedChainId = hexStripZeros(BigNumber.from(chainId).toHexString());
try {
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [
{
chainId: formattedChainId,
chainName: "CU Internal",
rpcUrls: ["http://myAddress"],
nativeCurrency: {
name: "ETH",
symbol: "ETH",
decimals: 18,
},
blockExplorerUrls: null,
},
],
});
} catch (error) {
console.error("error adding eth network: ");
}
}
This is the call I'm making
Same problem here, rpcUrls MUST be https, Metamask makes this check.
const firstValidRPCUrl = Array.isArray(rpcUrls)
? rpcUrls.find((rpcUrl) => validUrl.isHttpsUri(rpcUrl))
: null;
but specification is
All URL strings MUST include the protocol component of the URL. HTTPS SHOULD always be used over HTTP.

What do the keys in the '_performanceLogger' object of an XMLHttpRequest response mean?

I am trying to measure download (and later upload) speed using Axios in React Native. My question's relate to the most appropriate way to do so, and understanding if the _performanceLogger in the response from XMLHttpRequest is accurate for this purpose. There surprisingly doesn't seem to be much out there about _performanceLogger ... Appreciate the help!
A MWE is:
import React from "react";
import axios from 'axios';
// Dummy API endpoint
let requestURL = 'https://jsonplaceholder.typicode.com/users/2'
// Getting timestamp immediately before request is started
var startTimestamp = (new Date()).getTime()
// Make request through Axios
// Make a request for a user with a given ID
axios.get(requestURL)
.then(function (response) {
// Handle success
console.log("And I am burdened with glorious purpose.")
// Getting timestamp immediately after request is completed
let endTimestamp = (new Date()).getTime()
console.log("Request start time stamp: " + startTimestamp)
console.log("Request completed time stamp: " + endTimestamp)
// Logging the whole _performanceLogger object
let responsePerformanceLogger = response.request._performanceLogger
console.log('Perf Logger:')
console.log(responsePerformanceLogger)
// Logging the key/value specific to the actual request within the _performanceLogger object
let requestPerfString = 'network_XMLHttpRequest_' + requestURL
let responseTimespans = responsePerformanceLogger._timespans[requestPerfString]
console.log('Specific Request Timings:')
console.log(responseTimespans)
})
.catch(function (error) {
// Handle error
console.log("This is a mistake! I shouldn't be here!")
console.log(error);
})
.then(function () {
// always executed
console.log('For all time! Always!')
});
I use Expo to run this code on my device, and I get the following output to the console:
And I am burdened with glorious purpose.
Request start time stamp: 1640229022039
Request completed time stamp: 1640229022156
Perf Logger:
PerformanceLogger {
"_closed": false,
"_extras": Object {},
"_pointExtras": Object {},
"_points": Object {
"initializeCore_end": 194691080.25150004,
"initializeCore_start": 194691027.19495836,
},
"_timespans": Object {
"network_XMLHttpRequest_http://192.168.1.40:19000/logs": Object {
"endExtras": undefined,
"endTime": 194692352.89145836,
"startExtras": undefined,
"startTime": 194691383.22187504,
"totalTime": 969.6695833206177,
},
"network_XMLHttpRequest_http://192.168.1.40:19001/symbolicate": Object {
"endExtras": undefined,
"endTime": 194694267.96945837,
"startExtras": undefined,
"startTime": 194694100.6875417,
"totalTime": 167.2819166779518,
},
"network_XMLHttpRequest_https://jsonplaceholder.typicode.com/users/2": Object {
"endExtras": undefined,
"endTime": 194699846.2774167,
"startExtras": undefined,
"startTime": 194699738.0606667,
"totalTime": 108.21674999594688,
},
},
}
Specific Request Timings:
Object {
"endExtras": undefined,
"endTime": 194699846.2774167,
"startExtras": undefined,
"startTime": 194699738.0606667,
"totalTime": 108.21674999594688,
}
For all time! Always!
My specific questions are:
What are the different objects under the _timespans key? There are two (log, symbolicate) to the local IP for Expo ... what's happening here? Presumably these won't there when I deploy outside of Expo.
Is the third, the one that contains the actual URL made in the request, the actual timing of the download? (I've extracted this one as Specific Request Timings.) This is total download time (latency + file download), correct?
Is relying on the XMLHttpRequest timing less/more accurate than just using the simple getTime() timestamps that I have called before the request and after successful completion? I would expect that they should be close, but the getTime()'s require some finite execution time that could be variable by device/load.

Code was fine but not it's throwing error 403 - Failed to load resource: the server responded with a status of 403 (Forbidden) (Axios YouTube API)

I was following tutorial: https://blog.bitsrc.io/make-a-simple-react-app-with-using-youtube-api-68fa016e5a03.
I'm a noob so please, if you can help, pretend my name is Layman
I had actually finished, made it beautiful and was adding some additional things (like dislike buttons that dont do anything but look the part)
But now none of it works. I've even reverted my commits really far back to points where I know for show it works but I'm getting the same error. I can only assume its with youtube's api key but I dont know whats wrong. I noticed the issue when i tried to change the maxResults from 5 to 20. It did like that and it hasnt worked since.
I've made a new key, and used a try catch (i think ive done it right) and it still doesnt work
handle submit in App.jsx
handleSubmit = async (termFromSearchbar) => {
// alert(termFromSearchbar);
try {
const res = await youtube.get("/search", {
params: {
part: "snippet",
maxResults: 5,
key: process.env.REACT_APP_API_KEY,
q: termFromSearchbar,
},
});
this.setState({
videos: res.data.items,
selectedVideo: res.data.items[0],
});
} catch (error) {
console.error(error);
}
};
my .env file
import axios from "axios";
export default axios.create({
baseURL: "https://www.googleapis.com/youtube/v3",
params: {
part: "snippet",
maxResults: 5,
key: `${process.env.REACT_APP_API_KEY}`,
},
});
One possible explanation is that you've exceeded your quota (https://developers.google.com/youtube/v3/docs/errors)
You should verify that first. This document describes how you can do that (https://developers.google.com/youtube/v3/getting-started#quota)

Sending JSON via Postman causes an error in my Node.js service

I created schema in node.js. It worked before I included arrays.
This is my schema code:
const Item = new item_Schema({
info:{
title:{type:String, required:true},
bad_point:{type:Number, 'default':0},
Tag:{type:String, required:true}
},
review:{
Review_text:{type:Array, required:true},
Phone_list:{type:Array, required:true},
LatLng_list:{type:Array, required:true}
}
});
Item.statics.create = function(info, review){
const list = new this({
info:{
title,
bad_point,
Tag
},
review:{
Review_text,
Phone_list,
LatLng_list
}
});
return list.save();
};
This is my register code:
exports.register = (req, res) => {
const { info, review } = req.body
const create = (list) => {
return Item.create(info, review)
}
const respond = () => {
res.json({
message: 'place route registered successfully'
})
}
const onError = (error) => {
res.status(409).json({
message: error.message
})
}
RouteReviewItem.findOneBytitle(title)
.then(create)
.then(respond)
.catch(onError)
}
And this is the Postman JSON raw code:
{
"info":"{
"title":"test title",
"badPoint":"0"
"Tag":"tag1"
}",
"review":"{
"Review_text":["1번리뷰", "2번리뷰", "3번리뷰"],
"Phone_list":"["010-0000-0000", "010-1111-1111", "010-2222-2222"],
"LatLng_list":["111.1111,111.1111", "222.222,222.222","333.3333,333.3333"]
}"
}
This is the error I get in Postman:
SyntaxError: Unexpected token in JSON at position 17
at JSON.parse (<anonymous>)
at parse (C:\MainServer\node_modules\body-parser\lib\types\json.js:89:19)
at C:\MainServer\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\MainServer\node_modules\raw-body\index.js:224:16)
at done (C:\MainServer\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\MainServer\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a problem with postman? Or the node.js side?
I looked at the node.js book I was studying, but could not find any relevant information.
The code is fine, you have an issue with JSON you used for testing. For further testing and debugging, I suggest that you verify that the requests you send you the endpoint are correct by using a service like JSONLint (or any offlne tool that does the same). For the request you posted in the question, this service complains:
Error: Parse error on line 2:
{ "info": "{ "title": "test t
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Next time, before sending a request, make sure it is correct syntactically. That way you'll know that there is a problem with your code, and won't spend time debugging a non-existent issue.

Resources