Why am I getting missing access key error? - javascript

I am using the mediastack api for building a news app. But I am unable to put the api key correctly in the fetch request. The documentation says
http://api.mediastack.com/v1/news
? access_key = YOUR_ACCESS_KEY
my fetch request is like-
<!-- begin snippet: js hide: false console: true babel: false -->
fetch(`http://api.mediastack.com/v1/news
? access_key = ${API_KEY}
& keywords = tennis
& countries = us`)
.then((res) => res.json())
.then((data) => console.log(data));
I am getting the error missing access key . What am I doing wrong ?

Related

Query Building with Knex/Postgres (nested Json)

I'm trying to build a query that will change all 'assets' status to 'Pending Transfer' where location equals the location in the request's body data.
An entry on the "location" column in my "assets" table is as follows:
{"site":"Xxxxx, XX","site_loc":{"shelf":"89","unit":"89"}}
This is the knex query I'm trying to build:
async function bulkUpdate(req, res){
const site = req.body.data;
const data = await knex('assets')
.whereRaw(`location -> 'site' = '${site.physical_site_name}'`)
.update("status", "Pending Transfer") //todo: update history as well
.returning('*')
.then((results) => results[0]);
res.status(200).json({ data });
}
There error I'm getting is:
message: `update "assets" set "status" = $1 where location -> 'site' = 'Xxxxx, XX' returning * - operator does not exist: json = unknown`
I've also tried using:
async function bulkUpdate(req, res){
const site = req.body.data;
const data = await knex('assets')
// .whereRaw(`location -> 'site' = '${site.physical_site_name}'`)
.whereJsonPath('location', '$.site', '=', `${site.physical_site_name}`)
.update("status", "Pending Transfer") //todo: update history as well
.returning('*')
.then((results) => results[0]);
res.status(200).json({ data });
}
Where I get the error:
message: `update "assets" set "status" = $1 where jsonb_path_query_first("location", $2) #>> '{}' = $3 returning * - function jsonb_path_query_first(json, unknown) does not exist`
I can't tell if this is because I'm using the '->' operator incorrectly, or if there is a different comparison I should use other than '='. Should I not be using the apostrophe's around site?
I'm fairly new at this, but I've been trying to research this and have been trying various ways and have yet to figure it out.
Any help on understanding this better would be much appreciated. Thank you.
Ahh...
And the answer is:
.whereRaw(`location ->> 'site' = '${site.physical_site_name}'`)

Twitter API only posting to developer linked account?

I have been trying to play around with Twitter API and using the npm i twitter-lite library. I want for others to post something through my website when they click on post and sign in, however, it only posts to my developer account. The following is my code:
const config = require('./config');
const twitter = require('twitter-lite');
const client = new twitter(config);
client
.getRequestToken("website")
.then(res =>
console.log({
reqTkn: res.oauth_token,
reqTknSecret: res.oauth_token_secret
})
)
.catch(console.error);
client.post('statuses/update', { status: 'testing' }).then(result => {
console.log('You successfully tweeted this : "' + result.text + '"');
}).catch(console.error);
Appreciate any advice.

How to fetch correctly from server side in Node.js

I'd like to fetch/data and serverside fetch.
But I suffered following errors.
response.getCategory is not a function
(()=>{
const url = "/data";
fetch(url)
.then(response => {
console.log("getCategory_main.js",response.getCategory(1));
//displayQuiz(response,1);
});
})();
when we access /data, serverside fetch will be functioned.
const API_KEY="https://opentdb.com/api.php?amount=1&type=multiple";
const fetch = require('node-fetch');
const Quiz=require("../public/javascripts/quiz");
module.exports={
getQuiz:function(res){
fetch(API_KEY)
.then(response => response.json())
.then(json => { const quiz = new Quiz(json);
console.log("getCategory_model",quiz.getCategory(1));
console.log("quiz",quiz);
res.send(quiz);
});
}
};
I can get result
getCategory_model History
I should pass same data from serverside to clientside
but method access succeeded only in serverside..
What is the cause of this ? and how can I fix it ? thanks..
You can't send objects with live methods over the wire as JSON. That is, if your server side Quiz object has a getCategory() method, it won't have one when you send it over to the client.
You'll need to serialize it, e.g.
res.send({
quiz,
categories: [quiz.getCategory(1)],
});
When you fetch data, your'e fetching data (usually as text).
When you create a new quiz with new Quiz(json) your'e reading the json text data and using Quiz to create code from the json text.
So in your first example you should get the text result, and then evaluate the result to json so that you can use getCategory() from Quiz
const url = "/data";
fetch(url)
.then(data => data.json())
.then(json_text=> {
// here you use the text and parse to JSON
const data = JSON.parse(json_text)
// now you can create the Quiz object
const quiz = new Quiz(data)
console.log("getCategory_main.js", quiz.getCategory(1));
});

Undefined is not an object while trying to query nested objects. Using axios and React

The JSON response is as shown in the image 1.
I was able to assign the entire response using axios (which already does the JSON.parse) to the state (named profile).
while profile.bio and profile.image are working;
profile.user.username, etc are not working and throwing an error - Undefined is not an object
const [profile, setProfile] = useState({});
const phone_no = phone.phone;
const fetchProfile = useEffect(() => {
var res = {};
axios
.get('<API URL>' + phone_no)
.then((response) => (res = response.data))
.then(() => {
setProfile(res);
})
.then(() => console.log(profile))
.catch((e) => console.log(e)); });
const user_stream = {
name: first.first_name,
image: profile.image,
id: profile.user.id,
};
Update - Solution: Using async-await with axios, it's fixed.
profile or profile.user may still be undefined when trying to access it, so profile.bio is just undefined so it doesn't cause an error, but profile.user.username tries to access a property of an undefined object.
Try adding profile?.user?.username
Or profile && profile.user && profile.user.username
This will ensure that it only tries to render the username if profile is already defined

Fetch recursion using javascript to call Google place API

I need to get a list of results from a Google place API request. The API allows 20 results per page ans I need all results available so I need to go to the next page.The next page is accessible from a token given in the response of the previous request.
I've implemented the code below:
function request(url){
return fetch(url)
.then((response) => response.json())
.catch((error) => console.log(error))
}
This is my recursive function:
export function getListOfActivitiesInACity(city_name,nextPageToken,datas){
const first_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=activity+in+'+city_name+'&key='+ API_TOKEN +'&language=fr'
const next_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken='+nextPageToken+'&key='+ API_TOKEN
var url = nextPageToken ===''? first_url : next_url;
return request(url)
.then((data) => {
const newData = [...datas, data];
if(data["next_page_token"] !== undefined){
return getListOfActivitiesInACity(city_name,data["next_page_token"],newData);
}
return newData;
})
}
And then I call my function and print results
var datas=[];
getListOfActivitiesInACity("Lyon",'',datas)
.then(data => {console.log(data);})
The first iteration of the fetch works fine and gives me the good new url for the next fetch
(I tried it on my broser directy and it works)
But the second fetch return me this :
Object {
"html_attributions": Array [],
"results": Array [],
"status": "INVALID_REQUEST",
}
I really don't understand why it doesn't work , so please can anyone help Thanks

Categories

Resources