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
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'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);
});
}, []);
Hello I am using axios with react and and I have a problem with the first time requests. Every time my web has a full refresh then it is suppose to make two requests to the server:
to load the web global content
the child should load the current page related content
However, when I refresh the page, since the web global content is loaded in the App.js compontDidMount, then the global content is loaded, however for HomePage.js which in this case is the child component to App.js send the request in compontDidMount but checking the server logs, only the option handshake request is received and not the actual get request to get the page related content, however since am using react-router-dom's Link to navigate. If I navigate to another page then come back to home page then I get all the content since in that case the App.js compontDidMount will not be executed. could anyone help or explain why this is happening please
my hoempage.js componentDidMount
looks like this
axios.defaults.xsrfCookieName="csrftoken"
axios.defaults.headers = get_headers()
axios.get(`${API_URL}/dns/`).then(res=>{
this.setState({
top6:res.data.top,
latest:res.data.latest
})
})
my App.js componentDidMount is calling a functions in another file that uppdates redux and looks like this
componentDidMount() {
this.props.loadGlobal();
}
loadGlobal looks like this
export const getGlobal = () => {
return dispatch => {
dispatch(getGlobalStart());
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.headers = get_headers();
axios.get(`${API_URL}/api/get-global/`)
.then(res => dispatch(getGlobalSuccess(res.data)))
.catch(err => {
console.log(err.message)
dispatch(getGlobalFail(err.response.data))
}).catch(err=>{
dispatch(setAlert({ "show": true, error: true, "message":"network error fetching data, check your internet and try again or contact side admin if your network is fine"}))
});
};
};
my get_headers() looks like this
function get_headers() {
var headers = {
"Content-Type": "application/json",
};
if (localStorage.getItem('token')) {
headers = {
"Content-Type": "application/json",
"Authorization": `Token ${localStorage.getItem('token')}`,
};
}
return headers
}
i my backend am using django which fetching data from postman or even visiting the url works just fine for me
I am trying to create a post using LARAVEL 5.7 local REST api using a React app. I am using axios.post method with crossOrigin:true . I do not understand why get is working and post is not working. Laravel api is on wamp based localhost and React app is running at localhost:3000 My actions/index.js is as follows and the relevant action creator is addPost():-
import axios from 'axios';
export const FETCH = 'FETCH_POSTS';
export const ADD = 'ADD_POST';
const URL = 'http://postsapi.test/api/v1';
export function fetchPosts(){
const url = `${URL}/posts`;
const request = axios.get(url, { crossDomain: true });
//console.log(request);
return{
type: FETCH,
payload: request
}
}
export function addPost(post){
const url = `${URL}/posts`;
console.log(url);
const request = axios.post(url,post);
//console.log(request);
return{
type: ADD,
payload: request
}
}
This is the snap shot from browser that shows in preflighted request Access-Control-Allo-Origin is set twice as well
And in console I am getting this issue
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://postsapi.test/api/v1/posts. (Reason:
Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed).
This happens because the server and client is on different origins.
To overcome this you have to enable Cross-Origin Resource Sharing in your Laravel server as a middleware.
This thread might help you.
I am working with the CryptoCompare API to get data about cryptocurrencies for my project. I've made a few requests to the API and have had no issue getting a response.
Some of the queries for the API look like this:
https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR
And others look like this:
https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD
When I make requests to URLs that look like the first I am able to get a response from the API and retrieve the data. When I make the same request but for one of the URLs that look like the second I get an error. Error: Network error is all it says.
Here's what my code looks like:
import React, { Component } from 'react';
import axios from "axios";
class CoinInfo extends React.Component {
constructor(props) {
super(props);
this.state = {
coinInfo: []
}
}
componentDidMount() {
axios.get(`https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD`)
.then(res => {
const info = res.data;
this.setState({ coinInfo: info});
console.log(info);
});
}
render() {
return (
<div className="container">
</div>
)
}
}
export default CoinInfo;
If I swap out the URL in the Axios request and replace it with the other API endpoint/URL it works perfectly fine. It also works fine with any of the other CryptoCompare endpoints that have the root "min-api.cryptocompare.com".
However all the endpoints that follow the "www.cryptocompare.com/" pattern don't work.
I am not getting a CORS error. Just an error that says "Error: Network error" in Firefox.
Is this a problem with the API itself? Or is there something on my end I am overlooking?
axios.get(`https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD`)
its incorrect format I think so please retype it as
axios.get("https://www.cryptocompare.com/api/data/coinsnapshot/?fsym=BTC&tsym=USD")