app.post("/",function(req,res){
// console.log(req.body.crypto);
request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){
console.error('error:', error);
console.log(response.statusCode);
});
From the documentation:
All requests to our API must be authenticated with your public key.
First register an account.
Then choose one of our plans from the plans page.
Finally get your public key from the main dashboard.
You're not passing any key in your request.
You are seeing that error with 403 (Forbidden) status code because the API you are trying to use requires an API key. You can see it in their API documentation.
What you should do is following the steps mentioned in API documentation and get a API key. Then you should to use this API key as x-ba-key header for your future requests like below:
I suggest you to use axious package to make your API calls since request module is deprecated and they will not support future issues and versions. Install axios package using npm install axios command and then import it to your application file. Then make a request to the endpoint with your API key like this:
const options = {
headers: { 'x-ba-key': 'yourAPIKey' }
};
axios.get('https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR', options)
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
Related
I am trying to create a react App where I need to parse some RSS news feeds from url "https://news.google.com/news/rss" but I am getting an error "request has been blocked by CORS policy: "No 'Access-Control-Allow-Origin' header is present on the requested resource". I did the similar project in Android app where I fetched some feeds using AsyncTasks in java it didn't showed me any CORS issue, I want to understand why it worked on Android app and not in Web Application? Is it the browser that is enforcing the CORS or is the google server that is enforcing some sort of CORs policy?
let xmlText;
axios
.get(
"https://news.google.com/news/rss",
)
.then((response) => {
xmlText = response;
return response;
})
.then((textResponse) => {
console.log("Fetching response as", textResponse);
xmlText = textResponse;
})
.catch((error) => {
console.log(error);
});
You can use a plugin
google-news-json
Google News JSON API
Installation
npm install --save google-news-json
Or
yarn add google-news-json
Usage
Usage example:
let googleNewsAPI = require("google-news-json");
let news = await googleNewsAPI.getNews(googleNewsAPI.TOP_NEWS, null, "en-GB");
Also supports callback
googleNewsAPI.getNews(googleNewsAPI.SEACRH, "apple", "en-GB", (err,response) => {
console.log(response);
});
Parameters
Method (defaults to TOP_NEWS or HIGHLIGHTS)
Query (this is ignored when method is TOP_NEWS or HIGHLIGHTS)
Locale (defaults to en-GB)
Callback (not required)
Methods
HIGHLIGHTS, TOP_NEWS, LOCATION, SEARCH, TOPIC, GEO
Supported TOPICS
TOPICS_WORLD, TOPICS_NATION, TOPICS_BUSINESS, TOPICS_TECHNOLOGY, TOPICS_ENTERTAINMENT, TOPICS_SCIENCE, TOPICS_SPORTS, TOPICS_HEALTH
I am trying to fetch food by its key. In postman api is working fine but is the forntend it has no response.
backend code
app.get('/foods/:key', (req, res) => {
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
res.send(documents[0])
})
})
frontend code
const { key } = useParams()
const [foodById, setFoodById] = useState({})
useEffect(() => {
fetch(`http://localhost:5000/foods/${key}`)
.then((res) => res.json())
.then((data) => {
setFoodById(data)
})
}, [key])
Although you've added some images above, the most important is missing, namely, what are the Browser's Developer Tools stating the problem is. You should see some message in the Console tab, as well as in the Network tab for that particular request, if it is indeed being made. Until anyone sees this, it will be very difficult to help in fixing your problem.
If your not already, I suggest scaffolding any react app with create-react-app (CRA). This will give you a working app to start from. You can ignore CORS related issues in development, if using CRA, by adding "proxy": "http://localhost:5000", to your package.json file, see here for more on this method, but remember, this is only works for local development. You can also start Chrome to ignore Web Security by running it with the --disable-web-security flag e.g. chromium --disable-web-security, but that isn't a great idea really, more a way to quickly determine if you are having CORS problems, as Chrome masks some problems as CORS related, when in fact they aren't.
I'd also suggest changing your fetch code to use await, so instead you'd have:
const response = await fetch(`http://localhost:5000/foods/${key}`);
if (!response.ok) {
console.error(`Error message: ${response.statusText} ${response.status}`);
}
const result = response.json();
console.log(result);
This isn't necessary, but I've always found it way easier to read than the then/catch/finally method.
Reason for error
You need to stringify an object before sending it to the client with the JSON.stringify() method. When we exchange data to/from a web server, it must be a string.
Solution:
Proper way to send response to the client would to wrap the entire API in a try-catch block and explicitly specify the HTTP Status Code along with the stringified data in every response.
Note: Although 500 status code is used for error handling, you should choose one as per the use case.
app.get('/foods/:key', (req, res) => {
try {
/*
rest of the code
*/
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
if (err) {
// 500 stands for internal server error
return res.status(500).send(JSON.stringify('Here goes a meaningful error message!'));
}
// 200 stands for success
res.status(200).send(JSON.stringify(documents[0]));
});
/*
rest of the code
*/
} catch (error) {
// 500 stands for internal server error
res.status(500).send(JSON.stringify('Here goes another meaningful error message!'));
}
})
The problem is that you haven't set the CORS headers of response in your backend code. and you are using different ports in your backend and frontend (5000 & 3000) so the Same Origin Policy disallows reading the remote resource, indicating that the request was blocked due to violating the CORS security rules.
you've to set the CORS headers.
you can install the CORS npm package and follow it's instructions to resolve the issue like this:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
.
.
.
And one other issue that I'm seeing is that you've put the react-router default route before your specified path. so move the <route path="*"> after <route path="/foods/:key">
I am trying to implement a project in Vuejs with this https://www.twilio.com/code-exchange/one-time-passcode-verification-otp. I deployed my functions through this.
I have a custom vuejs app that I’m using this in a form with.
Here is my front end function
verifyNumber() {
var auMobilePrefix = “+61”;
var m = this;
m.mobileNumber = ‘’;
m.mobileNumber = auMobilePrefix.concat(this.finalModel.mobile);
// console.log(m.mobileNumber);
const code = this.vcode;
const data = new URLSearchParams();
data.append(“to”, m.mobileNumber);
data.append(“verification_code”, code);
fetch(“https://verify-xxxx-xxxxx.twil.io/check-verify”, {
method: ‘POST’,
body: data
})
.then(response => response.json())
.then(json => {
if (json.success) {
console.log(json.message);
} else {
console.log(json.message);
}
})
.catch(err => {
console.log(err);
});
}
After I validate the code. I get the following error in console:
Verify-xxxx-xxxxx.twil.io/check-verify:1 Failed to load resource: the server responded with a status of 404 ()
MultiStepVerification.vue?280d:214 The requested resource /Services/VAxxxxxxx/VerificationCheck was not found
How do I resolve this issue?
Update
https://www.twilio.com/docs/verify/api/verification-check
This is actually the intended behaviour.
Twilio deletes the verification SID once it’s:
expired
approved
when the max attempts to check a code have been reached
Under the verification service logs I noticed that the Status for my tests were Approved.
Can you check the Twilio Helper Library version, to make sure it is current?
twilio-node changelog
You can manually add a Twilio helper library version to your Twilio Function NPM Dependencies to override the older version used by default, which is currently 3.29.2.
Displays Node Version and Twilio Helper Library Version
I am working with Sheetlabs to turn a Google Sheet into a full API. I'm having trouble finding helpful information online besides the Sheetlabs documentation, because it seems like a fairly small service at this point.
I'm using axios within a custom function in Twilio to post information to our Sheetlabs API. The API requires HTTP Basic authentication.
I've tried all sorts of variations on my axios call, trying to follow the Sheetlabs SwaggerHub Documentation but I'm running out of ideas.
const url = 'https://sheetlabs.com/records/{organization}/{dbName}';
const postData = {
trackingid: `${trackingUrl}`,
phonenumber: `${userPhoneNumber}`
}
const authParams = {
username: //sheetlabs email,
password: //access token
}
// axios function
axios.post(url, postData, {auth: authParams}).then(response => {
console.log('response: ', response);
}).catch(err => {
console.log('axios sheetlabs post error catch: ', err);
});
Any help would be greatly appreciated. I'll do my best to provide you with any additional information you need.
AJAX by default sends data in the application/x-www-form-urlencoded format, but Axios sends it as JSON. I mention AJAX because in the example page they're using $.ajax to do a network request.
Axios mentions this default on their Github here and it's something I've run into on many servers who aren't sent up to receive JSON. It might be worth a shot to try doing an npm install qs and seeing if it helps you out:
const qs = require('qs');
axios.post(url, qs.stringify(postData), {auth: authParams}).then(response => {
console.log('response: ', response);
}).catch(err => {
console.log('axios sheetlabs post error catch: ', err);
});
I reached out to Sheetlabs Support and at this time they don't support adding new records to a Google Sheet via posts. Could have sworn I saw that capability in their documentation and API though. Thank you for your responses.
I'm trying to fetch data from http://www.recipepuppy.com/api/?q=onion&p=1. (Sample query)
It works in a browser, but I was trying to fetch it inside my React app and I'm encountering “No 'Access-Control-Allow-Origin' header is present on the requested resource error.
So I changed my strategy and now I'm trying to use JSONP (https://github.com/mzabriskie/axios/blob/master/COOKBOOK.md#jsonp).
But I can't make it work. I'm getting this error all the time. Can someone please help me with my issue?
Error:
Uncaught ReferenceError: jp0 is not defined
at ?q=onion&p=1&callback=__jp0:1
My Code:
import jsonp from 'jsonp'
export const FETCH_RECIPES = 'FETCH_RECIPE'
export const SHOW_INFO = 'SHOW_INFO'
export function fetchRecipes (searchTermToDOoooooooooo) {
const request = jsonp('http://www.recipepuppy.com/api/?q=onion&p=1', null, function (err, data) {
if (err) {
console.error(err.message)
} else {
console.log(data)
}
})
return (dispatch) => {
/*
request.then(({ data: data1 }) => {
dispatch({ type: FETCH_RECIPES, payload: data1 })
})
*/
}
}
export function showInfo (info) {
return {
type: SHOW_INFO,
payload: info
}
}
How that error looks in dev tools:
You can't do it with client-only code, at least not with JSONP+Axios (Axios doesn't (natively) support JSONP; the "jsonp" library is different from Axios), because it's the server you're getting information from that's in violation of the cross-origin rules. In this case, it's Recipe Puppy that isn't set up for Access-Control-Allow-Origin headers.
One option is to use a server-side proxy, as #Pointy mentions.
Your flow would then shift to:
Client calls server-side proxy for information.
Proxy calls Recipe Puppy's API and translates or passes through information as needed.
Proxy relays that information to the client-side code for further processing.
As for your current shift to jsonp, it appears the jsonp library is not exporting jp0 properly for some reason. This could be an error with your build tool. You'll want to double-check your setup and make sure your build tool is picking up the jsonp library and actually putting it into the compiled source.