I'm fetching a json file using axios in my react project. The rquest is made and I get a response on my localhost. However, on github pages when I deploy, the request is not made.
I double checked using the networks tab in chrome devtools.
My code
the url I'm requesting: here
You are making the request when your component unmounts (cleanup function) instead on its mount. Instead of returning a function in useEffect you should do the request directly.
useEffect(() => {
axios.get('https://scaleflex.cloudimg.io/v7/0.fe_task_static/pictures.json?vh=7a646d&func=proxy').then((res) => {
setImages(res.data);
});
}, []);
Related
I am using React.js 18 version. Facing CORS issue on a piece of code while making post request using axios. Intentionally not putting the original URL of post request. Attaching API response screenshot files below the code.
I am getting response in postman but not in browser(CORS). All I know from my colleague, this API is build on PHP and according to backend guy things are fine on his side.
I am putting this code here to know what are we doing wrong on front end? We are stuck here since yesterday.
Please help!
console response : https://i.stack.imgur.com/HbUjq.png
network response : https://i.stack.imgur.com/6xycq.png
network response : https://i.stack.imgur.com/5cjey.png
postman response : https://i.stack.imgur.com/MxyDT.png
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [CaseDetail, setCaseDetail] = useState([]);
const getCaseDetail = async () => {
const casedetail = {schemeNameDratDrtId:'1',casetypeId:'1',caseNo:'1',caseYear:"2020"};
await axios.post('URL', casedetail,
{
headers: {"Access-Control-Allow-Origin": "*"}
}
)
.then((result) => {
setCaseDetail(result.data.data)
})
}
useEffect(() => {
getCaseDetail();
}, []);
console.log(CaseDetail)
return (
<div className="App">
<h2>Welcome to Home Page</h2>
</div>
);
}
export default App;
Your server should enable the cross-origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
This is a security issue from the browser. If you get 200 using postman, this means the problem is that the browser is blocking it. Try to play this again using API testing website like: "reqbin.com", if that works, the backend guys should fix the header problem. I hope this helps.
some possiable things that might help:
I am getting response in postman but not in browser(CORS) - this is noraml for CORS problem.
there can be a differnce betweeen fetach and axios requests. so check if fetach works. if so check
Axios fails CORS but fetch works fine
if you need to send a token in a header , make sure that the axios sends it
see
How to set header and options in axios?
I have build a simple pure react and meteor web app. I am trying to connect a flask API to my meteor.js app for the machine learning component of my application. I have seen examples for pure react front end but cant get the same logic to work for meteor.
what I did is:
make a flask app and return the prediction results to localhost:5000 as a python dictionary e.g.
{'class': 'bird', 'confidence':'0.8932'}
Set up a proxy in my meteor app in package.json, I have meteor app running at localhost:3000:
"proxy":"http://127.0.0.1:5000/"
finally, this is where I am confused, I have a bunch of components in my home page, I am not sure if I have to render the flask results in a component or page, nor how to do that. What I tried Is to render the results in one of the components using the useEffect, useState functions.
I get an error that says something like I can't use this funtionality.
function App() {
const [predictedClass, setPredictedClass] = useState(0);
useEffect(() => {
fetch('/prediction').then(res => res.json()).then(data => {
setPredictedClass(data.class);
});
}, []);
I use the useEffect method to get the data from the requests of my api.
example:
const [data, setData] = useState(null);
useEffect(() => {
getData('GET', '/api/test')
.then(response => {
setData(response)
})
.catch(error =>
console.log(error)
);
}, []);
Where getData is a custom function that calls an axios request.
I'm making react app which search on Youtube and show some list of video by using create-react-app.
My problem is the document of response from axios.get() only contains scripts and empty skeleton tag.
I want this has some contents inside of it like when opened from browser. why this happen? and what should i study?
import React from "react";
import SearchBar from "./SearchBar";
import axios from "axios";
class App extends React.Component {
onSubmitFormSearch = async (text) => {
console.log("axios", text);
const response = await axios.get(`/results?search_query=${text}`, {
responseType: "text",
responseEncoding: "utf8",
});
console.log(response.data);
};
render() {
return <SearchBar onSubmitForm={this.onSubmitFormSearch} />;
}
}
export default App;
this is my react code
here's document of response https://codepen.io/im0505/pen/MWaMKXa
You will not get the complete webpage just like you see in browser when visualising the response of axios.get. The fundamental reason is that when you load an URL in browser, browser executes the scripts from the response of the request which doesn't happen when visualising response of request made by axios.
What Happens When You Type in a URL : Source
You enter a URL into a web browser
The browser looks up the IP address for the domain name via DNS
The browser sends a HTTP request to the server
The server sends back a HTTP response
The browser begins rendering the HTML
The browser sends requests for additional objects embedded in HTML (images, css, JavaScript) and repeats steps 3-5.
Once the page is loaded, the browser sends further async requests as needed.
Points 6 and 7 doesn't happen when you are looking at the result in Codepen or in your axios response
i'm studying hooks on reactjs with an api to request data, i would like to know if theres a way to request all pages at once and show the datas at the page. The api im using its from Rick and Morty API https://rickandmortyapi.com/api/character/ and you can see the result here https://project-soctest.herokuapp.com/
this is what i made so far using useEffect
useEffect(() => {
async function loadData() {
const apiResponse = await api.get(`?page=1`);
setCharacters(apiResponse.data.results);
}
loadData();
}, []);
No there is no way to get all the pages in this particular API.
I'm building an electron wrapped react app. Generally, using create-react-app, I can specify a proxy in the package.json so that axios knows to use a different PORT during development. However, I think the electron piece is doing some overriding because even though react runs on 3000 by default, all my axios requests are routed to :5000 which is the electron port. Anyone know how to get axios to use a different port?
You can try to create a custom instance of axios and use it instead.
axiosConfig.js
const customAxiosInstance = axios.create({
baseURL: 'localhost:5000',
});
The below code comes where you call the endpoint of the API
import APIEndPoint from './axiosConfig';
APIEndPoint
.get('/your-end-points-here')
.then((response) => {
// handle success
})
.catch((error) => {
// handle error
})
})
Though not an answer to your question but if your intent is communicating between react-app and electron then I would suggest using IPC(ipcMain & ipcRenderer) calls to communicate between your react-app and electron. Please refer to the below links.
https://electronjs.org/docs/api/ipc-main
https://electronjs.org/docs/api/ipc-renderer