Anyone familiar with the OpenWeather API and having any issues with it since lately?
I am following along with Stephen Grider's React and Redux course where I have to get an API connection with them, this went okay until today, now I am getting a 404 error? Anyone familiar with this?
This is my code:
import axios from "axios";
const API_KEY = "3ce22afbb4c9b6c452574b28666ed63d";
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;
export const FETCH_WEATHER = "FETCH_WEATHER";
export function fetchWeather(city) {
const url = `${ROOT_URL}&q=${city},us`;
const request = axios.get(url);
return {
type: FETCH_WEATHER,
payload: request
};
}
I have edited out the first 3 and last 3 characters.
Related
i was trying to fetch a data for a project but everytime i'm converting the fetch data to json it returns me
SyntaxError: Unexpected token < in JSON at position 0
i don't understand why it's showing me this
import React,{useContext,useState,useEffect} from 'react'
const url = 'www.thecocktaildb.com/api/json/v1/1/search.php?s='
export default function AppProvider({children}) {
const [loading,setLoading] = useState(true)
const [searchTerm,setSearchTerm] = useState('a')
//set it as 'a' for suggestion at search bar at beginning.
const [cocktails,setCocktails] = useState([])
const fetchUrl = async ()=>{
setLoading(true)
try {
const response = await fetch(`${url}${searchTerm}`)
//(${url}${searchterm} helps me to fetch data at first with names that starts with 'a' for suggestion///
const data = await response.json()
setLoading(false)
} catch (error) {
console.log(error)
}
}
useEffect(()=>{
fetchUrl()
},[searchTerm])
please visit the API page from the URL & see if there's an issue with the data. the data is not fetching. what's the issue?
Link
Doing
fetch('www.thecocktaildb.com/')
will fetch not that website, but that path relative to the current path. For example, doing so here on Stack Overflow results in the URL being fetched being
https://stackoverflow.com/questions/72914244/www.thecocktaildb.com/
which, of course, doesn't exist - and presumably that URL doesn't exist on your site either.
Use the full path.
const url = 'https://www.thecocktaildb.com/api/json/v1/1/search.php?s='
I'd also recommend only calling the API when searchTerm isn't empty, and perhaps add a debounce of a few hundred milliseconds so as not to call it too often and to keep the client from being blocked.
i tried fetching an api request from https://suggestqueries.google.com/complete/search? but it is getting back this error "Uncaught SyntaxError: Unexpected token '<'". here is my code
import React, { useState } from 'react';
import suggestSearch from "../../Apis/suggestSearch";
const getSuggestions = () => {
const [autoSearchData, setAutoSearch] = useState("");
const getAutocomplete = async () => {
const response = await suggestSearch.get("", {
params: {
q: searchQuery,
}
});
setAutoSearch(response.data[1]);
console.log(setAutoSearch);
console.log(autoSearchData);
};
}
here is the suggestSearch code
import axios from "axios";
import jsonpAdapter from "axios-jsonp";
export default axios.create({
baseURL: "https://suggestqueries.google.com/complete/search?",
adapter: jsonpAdapter,
params: {
hl: "en", // Language
ds: "yt", // Restrict lookup to youtube
client: "youtube" // force youtube style response, i.e. jsonp
}
});
This error happens because you are referring to an asset that no longer exists. Check your API request link to see if it is still a valid asset.
From the baseURL I'm inferring that you're trying to do a application/x-www-form-urlencoded request.
For such a request to succeed in axios, you will have to import the querystring module and then do axios.post(baseURL,qs.stringify({data}),config). In this case, const qs=require('querystring');.
When trying to use axis to query an external Weather API, I get this error
ReferenceError: axios is not defined
at getTropicalCyclones (vm.js:16:9)
Here is my action for getTropicalCyclones {}
(of course I have to hide my client ID and secret)
const getTropicalCyclones = async () => {
const BASE_WEATHER_API = `https://api.aerisapi.com/tropicalcyclones/`
const CLIENT_ID_SECRET = `SECRET`
const BASIN = `currentbasin=wp`
const PLACE = `p=25,115,5,135` // rough coords for PH area of responsibility
const ACTION = `within` // within, closest, search, affects or ''
try {
let text = ''
let response = {}
await axios.get(
`${BASE_WEATHER_API}${ACTION}?${CLIENT_ID_SECRET}&${BASIN}&${PLACE}`
)
.then((resp) => {]
response = resp
text = 'Success retrieving weather!'
})
.catch((error) => {
console.log('!! error', error)
})
const payload = await bp.cms.renderElement(
'builtin_text',
{
text,
},
event.channel
)
await bp.events.replyToEvent(event, payload)
} catch (e) {
// Failed to fetch, this is where ReferenceError: axios is not defined comes from
console.log('!! Error while trying to fetch weather info', e)
const payload = await bp.cms.renderElement(
'builtin_text',
{
text: 'Error while trying to fetch weather info.',
},
event.channel
)
await bp.events.replyToEvent(event, payload)
}
}
return getTropicalCyclones()
So my question is, how do I import axios? I've tried
const axios = require('axios')
or
import axios from 'axios';
but this causes a different error:
Error processing "getTropicalCyclones {}"
Err: An error occurred while executing the action "getTropicalCyclones"
Looking at the package.json on GitHub, it looks like axios is already installed
https://github.com/botpress/botpress/blob/master/package.json
However, I cannot locate this package.json on my bot directory...
Secondly, based on an old version doc it looks like this example code just used axios straight
https://botpress.io/docs/10.31/recipes/apis/
How do I use axios on Botpress?
Any leads would be appreciated
Botpress: v11.0.0
Simply use ES6 import.
include this line at the top of your code.
import axios from 'axios';
Note: I'm expecting that the axios is already installed
I have react+redux application and I want to replace rest-requests in my actions to grapqhl-requests. What is the most simple method to do it?
I read about apollo, but I just to want add graphql in my existing requests.
You must change the way you will get the data because Apollo is a layer between you and the Api requested where you can join many Apis into one single query call.
The example above is very simple and just to explain the way will place your querys and how it connects to Apollo Server. You can set middlewares to log requests on add some headers too.
You will install [https://github.com/apollographql/react-apollo] and [https://github.com/apollographql/graphql-tag]
After that create a connection file in your project that imports
graphClient.js
import { ApolloClient, createNetworkInterface } from 'react-apollo';
const networkInterface = createNetworkInterface({
uri: 'yourserver address'
});
const client = new ApolloClient({
networkInterface,
});
export default client;
yourRequestFile.js
import gql from 'graphql-tag';
import client from './graphClient';
export const getYourData = () => ({
query: gql`
query {
products() {
info {
value {
qty
value
}
}
}
}`,
});
const returnYourData = async () => client.query(getYourdata());
export default returnYourData;
I would like to add auth token to http request header every time a http request sent and if authorization fails, I want to redirect user to the login. Should I decorate Http Driver or is there a better way to do it?
I came with a solution that decorates http driver. But I'm not sure this is the correct way of doing it. Here's the code so far I have written:
import Rx from 'rx';
import {makeHTTPDriver} from '#cycle/http';
function makeSecureHTTPDriver({eager = false} = {eager: false}) {
return function secureHTTPDriver(request$) {
const httpDriver = makeHTTPDriver(eager);
const securedRequest$ = request$
.map(request => {
const token = localStorage.getItem('token');
if (token) {
request.headers = request.headers || {};
request.headers['X-AUTH-TOKEN'] = token;
}
return request;
});
const response$ = httpDriver(securedRequest$);
//todo: check response and if it fails, redirect to the login page
return response$;
}
}
export default makeSecureHTTPDriver;
Here is the code how I use makeSecureHttpDriver
const drivers = {
DOM: makeDOMDriver('#app'),
HTTP: makeSecureHttpDriver()
};
This is a little late, I don't frequent SO very much. I'd suggest using other drivers instead to avoid placing any logic in your drivers.
import storageDriver from '#cycle/storage'
import {makeHTTPDriver} from '#cycle/http'
function main(sources) {
const {storage, HTTP} = sources
const token$ = storage.local.getItem('token')
.startWith(null)
const request$ = createRequest$(sources)
const secureRequest$ = request$.withLatestFrom(token$,
(request, token) => token ?
Object.assign(request, {headers: {'X-AUTH-HEADER' : token }) :
request
)
return {HTTP: secureRequest$, ...}
}
Cycle.run(main, {
...
storage: storageDriver,
HTTP: makeHTTPDriver()
})
I'm not sure if this will help but HTTP driver is superagent under the hood so you can pass it an object like with required info like here.
But in regards to your issue I think that the HTTP driver might need this option added to the driver it self so you can dictate if the driver should be secure or not eg:
const drivers = {
DOM: makeDOMDriver('#app'),
HTTP: makeSecureHttpDriver({secure:true})
};
Because your implementation looks ok to me, it might be worth having it in the driver itself.
I'd create an issue in the HTTP driver repo and see what the community think, you can also ask people to interact via the gitter channel :-)