I am doing little project to learn and put it in my project section
I get problem like this:
GET https://cors-anywhere.herokuapp.com/http://www.recipepuppy.com/api/?q=rice 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
I tried with using axios headers (i found this sugestion on another forum but it dosn't work)
My code for fetching data looks like this
export async function fetchData(text) {
const proxy = `https://cors-anywhere.herokuapp.com/`;
const base = `http://www.recipepuppy.com/api/`;
const baseEnd = `q=${text}`;
const data = await axios
.get(`${proxy}${base}?${baseEnd}`)
.then(data =>console.log(data));
const recipes = data.data.results;
return recipes.length > 0 ? recipes : false;
}
function called here:
async function getRecipes(e){
e.preventDefault();
const text = e.target[1].value;
const loader = '<div class="loader"></div>';
container.insertAdjacentHTML('beforebegin', loader);
const recipes = await fetchData(text);
document.querySelector('.loader').remove();
displayRecipes(recipes);
}
You need to catch possible error from Promise (as axios.get() return Promise type object).
axios.get(`${proxy}${base}?${baseEnd}`)
.then(data =>console.log(data))
.catch(error => {
console.log(error)
})
Related
The problem here is when every time I reload the page I'm getting this error.
which is the Uncaught (in promise) Error: Request failed with status code 500.
here's my code in list.tsx
const [state, setState] = useState([]);
const { getRoom } = useRoom();
const fetchData = async () => {
return getRoom().then((res) => setState(res['data'].data));
}
useEffect(() => {
(async function fetchData() {
await fetchData();
})();
})
code for room.tsx
function useRoom() {
const creds = useCredentials();
Axios.defaults.baseURL = serverConfig[creds.server].api;
return {
getRoom: (params?: object) => Axios.get(`${API_URL}/room` + (params ? getQueryParams(params) : ''))
};
}
500 is an error code servers produce. That's not necessarily something you can fix on the client. You'll need to understand which request the server returns a 500 to and why. Then maybe you can change something on the client (e.g. a malformed request). Or maybe you'll need to change something on the server.
Either way, looking only at the client-side JS code won't help you fix this.
I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}
according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.
When a user creates a post in my RESTful application, I want to set the response status code to 201.
I followed the documentation and created start/hooks.js as follows:
'use strict'
const { hooks } = require('#adonisjs/ignitor')
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', (status) => {
this.status(status).send(status)
})
})
Now in my PostController.js, I have this:
async store( {request, response, auth} ) {
const user = await auth.current.user
response.sendStatus(201)
}
But I am getting 500 HTTP code at this endpoint.
What am I doing wrong?
I noticed when I run Response.hasMacro('sendStatus') I get false.
In fact adonis already have this out of the box for all response codes...
Just write response.created(.....).
You can also use for example: .badRequest(), .notFound(), etc...
More info on: https://adonisjs.com/docs/4.1/response#_descriptive_methods
I solved this problem yesterday:
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', function (status) => {
this.status(status).send(status)
})
})
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 can't figure out why this code isn't passing the flow checker. I simply send an object to the updatePopper function and inside it I make an api call to update the data in the DB, and then I get a response, decode that response, and return that new updated data to the client-side and update the redux-form with the latest data. But flow doesn't like my code. Any ideas would be awesome!
This is the error popping up:
// Code in my react submit function
const newPopper: {data: Popper} = await this.props.updatePopper(data)
// Code in my redux action
export const updatePopper = (data: Popper) => async (dispatch: DispatchActionDynamic): {data: Popper} => {
// Make API REQUEST
const response = await PopperApi.updatePopper(popperData)
// Decode JSON
const body: PopperResponse = await response.json()
// Check for Valid response and error handling
await statusCheck(response, dispatch)
// update redux with new data
dispatch(updatePopper(body))
// return response
return body
}