How I can get response http url by axios in the server - javascript

I have a problem with axios in REACT, it works on local but does not work when I deployed it.
It say this : enter image description here
my Code :
import React, {useEffect, useState} from 'react';
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get("https://recvueadmin.hellow.fr/api/question")
.then((res) => console.log(res))
.catch((err) => console.log(err))
}, []);
I have this for CORS in the back-end :
app.use(cors());

Related

How can I use 'withRouter' and 'history push' in react router v6 for redirecting

I have registered a button that will take users to a login page on click. I tried using history.push() and include values entered into the form, but I do not know how to pass the value of userData because I get the following error:
refers this line payload: err.response.data()
When I change this line to display data in the console it is displayed correctly.
authAction.js
import axios from 'axios';
import { GET_ERRORS} from "./types";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import React from "react";
// Register User
export const registerUser = (userData,history) => dispatch => {
axios
.post('/api/users/register', userData)
.then(res => history.push('/login'))
// .then(res => console.log(res.data))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data()
})
);
};`
I tried to import the hooks version with router but it brings another error "Invalid Hook Call Warning"
export const registerUser = (userData,history) => dispatch => {
const navigate = useNavigate();
axios
.post('/api/users/register', userData,navigate)
.then(res =>navigate('/login'))
// .then(res => console.log(res.data))
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data()
})
);
};
What am I doing wrong?

App.js:13 Uncaught (in promise) SyntaxError: Unexpected end of input

Sending a fetch request to this API, though as the title states, keep getting unexpected end of input and I can't figure out why. Any solutions?
import './App.css';
import React, {useEffect, useState} from 'react';
const ART_API = "https://api.harvardartmuseums.org"
function App() {
const [anime ,setAnime] = useState([])
useEffect(() => {
fetch(ART_API, {mode: 'no-cors'})
.then((res) => res.json())
.then((data) => { console.log(data)})
}, []);}

ReactJS rendering Issue fetching an API

I'm trying to fetch a WeatherApp API, using Geolocation.
My problem is the rendering:
It doesn't allow me to render the page before I fetch (but after I somehow manage to fetch, the code seems to work).
Returning Error message:
Type Error : Cannot Read Property 'temp' of undefined
import React, { useState } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
// this line is returning the error
console.log(weather.main.temp)
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
Fetching weather and setting weather state is asynchronous, your are console logging weather.main.temp before the request has completed. And fetching data is side effect in reactjs. So you are suggested to fetch weather info by using useEffect hooks and set weather state there.
import React, { useState, useEffect } from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [ positionLat, setPositionLat ] = useState('') ;
const [ positionLong, setPositionLong] = useState('') ;
navigator.geolocation.getCurrentPosition(function(position) {
setPositionLat(position.coords.latitude);
setPositionLong(position.coords.longitude);
});
const [weather, setWeather] = useState('');
const fetchingWeather = () => {
Axios.get(
`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={API_KEY}&units=metric`)
.then((res) => {
console.log(res.data.main.temp)
setWeather(res.data)
})
}
useEffect(() => {
fetchingWeather();
}, [weather])
return (
<div className="App">
<p>lattitude :{positionLat}</p>
<p>longitude :{positionLong}</p>
<button onClick={fetchingWeather}>Cliquez moi pour fetch</button>
</div>
);
}
export default App;
That should work.

'login' is not defined error happens in React.js

I made frontend app in React.js.
I wrote codes in App.js of frontend like
import React, { Fragment, useState, useEffect, Component, View } from 'react';
import axios from 'axios';
import Routes from '../src/components/Routes';
import TopNavigation from './components/topNavigation';
import SideNavigation from './components/sideNavigation';
import Footer from './components/Footer';
import './index.css';
import Router from './Router';
const App = () => {
const [user, setLogin] = useState(null)
const [report, setReport] = useState(null)
useEffect(()=>{
login().then(user => setLogin(user))
}, [])
useEffect(()=>{
getReport().then(report => setReport(report))
}, [])
return <div>
{user != null? <p>name: {user.name}</p>:<button>Login</button>}
</div>
}
export default App;
I wrote in this code login().then(user => setLogin(user)) whether user already logined or not.
Login system was made in Django,so I want to use it.I think React has login method but I really cannot understand what is wrong.How should I fix this?
I can see nowhere login is defined in your code. If you've written login on other files, you should import it.
Actually, I cannot understand what you mean by this - "I think React has login method but ...". React doesn't support any predefined login method.
You should define login method yourself something like this.
const API_URL = 'some url';
const login = async (body) => {
const response = await axios.post(`${API_URL}/login`, body);
return response.json();
};
const App = () => {
const [user, setLogin] = useState(null);
const [report, setReport] = useState(null);
useEffect(() => {
login({
email: 'email#some.com',
password: 'some password'
}).then((user) => setLogin(user));
}, []);
useEffect(() => {
getReport().then((report) => setReport(report));
}, []);
};

Console log showing more than expected while using React Hooks

I am trying to fetch Data from an Api. I am getting the required result but when I try to console log it , it is console logging 4 times.
This is my app.js where I am using the fetchData.
import React, {useEffect, useState} from 'react';
import styles from './App.modules.css';
import {Header, Cards, Footer, Map, Table, Statecards} from './components/exports';
import {fetchData} from './api';
function App() {
const [data, setData] = useState({});
useEffect(() => {
const settingData = async () => {
const data = await fetchData();
setData(data);
}
settingData();
}, []);
console.log(data);
return <div className = {styles.container}>
<Header />
</div>
;
}
export default App;
This is the fetchData function
import axios from 'axios';
const url = 'https://api.covid19india.org/data.json';
export const fetchData = async () => {
try{
const response = await axios.get(url);
return response;
}
catch(err){
console.log(err);
}
};
The console.log in the app.js is giving 4 console logs as below
I am not being able to figure out what's wrong.
const settingData = async () => {
const data = await fetchData();
setData(data);
}
useEffect(() => {
settingData();
}, []);
try this one.

Categories