I am using axios to fetch data from aws.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function Employee() {
const[data, setData] = useState([]);
useEffect(() => {
axios.get('123.56.234.123:8080/employees?num=1')
.then(response => {
setData(response.data);
})
},[]);
return data;
}
From this code, I got the error message saying
Get http://localhost:8080/123.56.234.123:8080/employees?num=1 431(Request Header Fields Too Large).
I believe the cause is from the wrong url I am getting.
In this case, how can I fetch data from the endpoint?
PS) My node version: 14.XX
Thank you.
I think you need to set a PROXY. You have currently set the axios baseURL to be localhost:8080. That is why the get url is getting prepended to baseUrl.
The error 431(Request Header Fields Too Large) occurs because the Referrer url is too long.
If you are using create-react-app, then please refer this official documentation.
Related
Working locally, I'm trying to pull some data from an api endpoint into a react front-end. Here's what I have:-
Data source/api endpoint (api platform, symfony)
http://127.0.0.1:8000/api/users?page=1
Front-end, React
http://127.0.0.1:3000/
/src/App.js
import React from 'react';
fetch('http://127.0.0.1:8000/api/users?page=1')
.then(response => console.log(response))
.then(json => console.log(json))
function App() {
return (
<div className="App">
</div>
);
}
export default App;
Firstly, I had to overcome a CORS issue with my data source. In symfony;-
.env
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###
As a side note; For my api endpoint (data source) - I can return the json response fine using both cURL and postman. However, if I try directly in a browser address bar, I just get my api landing page back i.e. swagger doc.
I'm wondering if this is an issue with headers not being set?
Back in my react app http://127.0.0.1:3000/ and at the console;-
my response is showing a 200 as you can see from above, but my json variable has a length of zero? So, no data.
Any ideas on how to pull the data (json) through to my react app using the above technique?
Here's what I was looking for in the end...
import React from 'react';
import { useEffect } from 'react'
function App() {
useEffect(() => {
fetch("http://127.0.0.1:8000/api/users?page=1")
.then((response) => response.json())
.then((response) => {
console.log(response);
})
}, []);
return (
<div className="App">
</div>
);
}
export default App;
I've been trying to display the contents of a list using JSX in React. My server side is flask and serves JSON data to the react frontend. When I provide JSON data with only a simple dictionary with string keys and values, react can display it just fine, but when I try to use a list, and I've been messing around with this for 15 hours now, it just keeps saying "Uncaught TypeError: initialData.names is undefined". This error is consistent across different mehthods of requesting the data. If I choose to display initialData.names, there is an error that JSX can't display an object with keys of "name". But as soon as I try to access the data inside, it freaks out. I've never used Stack Overflow before so let me know if my question needs a different format.
routes.py
import json as JSON
from flask import render_template, jsonify
from api import app
from api.static import variables as VARS
#app.route("/regions")
def regions():
print("REGIONS")
'''
data = {"data":[{
"name": region_name,
"url": "/regions/" + region_name
} for region_name in VARS.region_names]}
'''
'''
data = {
"name":"ford"
}
'''
data = {
"names":[{"name":"ford"},{"name":"toyota"}]
}
return data
Regions.js --gets run from the main js file
import React, {useEffect, useState} from 'react'; //ES6 js
import {Link, useParams} from 'react-router-dom'
function Regions(){
const [initialData, setInitialData] = useState([{}]);
useEffect(() => {
fetch('/regions').then(
response => response.json()
).then(
data => setInitialData(data)
)
});
return(
<div>
<h1>Select a Region</h1>
{initialData.names.map(brand => (<h2>{brand.name}</h2>))}
</div>
);
}
export default Regions;
Js Error
I am building an app where the user connects to a server by entering the URL when logging in.
Each server provides an API and I can't hard-code the value for the BaseURL when creating the Axios client instance. I somehow need to globally store the URL and set it based on the user input in the login form.
So I would like to know what is a proper way to do this. I am really not sure what is the best approach to dynamically store a value that I can access when creating the API connection. Any ideas and best practice suggestions are welcome.
Here is the code for creating the API connection: client.js
import { create } from 'apisauce';
const api = create({
baseURL: "BASE_URL_FROM_USER_INPUT" + "server/odata/"
});
export default api;
This is how I use the API: users.js
import api from './client';
const getUsers = () => api.get("/users");
export default {
getUsers
}
This is how I will get my data:
import React, { useState, useEffect } from "react";
import usersApi from '../api/users';
const TestScreenAuthenticated = ({navigation}) => {
const [users, setUsers] = useState([]);
useEffect(() => {
loadUsers();
});
const loadUsers = async () => {
const response = await usersApi.getUsers();
setUsers(response);
}
...
};
export default TestScreenAuthenticated;
you can use the localStoreto store the baseUrl.
//save the value
localStore.setItem('baseUrl', value)
//read the value
localStore.getItem('baseUrl')
If you can use the .env file in your project and put the web service address there. This file is out of reach of the user viewing the site and will not be able to edit it
this link:
https://create-react-app.dev/docs/adding-custom-environment-variables/
when I tried to post some random data to firebase through axios from the js file, the error shown is given below.
_axios_order__WEBPACK_IMPORTED_MODULE_2___default.a.post is not a function.
the code is
//all import statements including axios and there is an axios file and it contains an axios baseURL.And the class definition.
purchasecontinueHandler=()=>{
const order={
ingredients:this.state.ingredient,
price:this.state.burgerprice,
}
axios.post('/orders.json',order)
.then(response => console.log(response))
}
this was my mistaken code, here I exported the 'instance' with a new method, unfortunately, that was not required.
import axios from 'axios';
const intsance=axios.create({
baseURL:'https://burger-d4f0a.firebaseio.com/'
});
export default new intsance();
just define as
import axios from 'axios';
const intsance=axios.create({
baseURL:'https://burger-d4f0a.firebaseio.com/'
});
export default intsance;
Hi I am trying to fetch data from backend using an api but the api is returning 404 error. In postman it is working fine. Can someone look in the code and tell where am I going wrong:
import axios from "axios";
function fetchData(email, password) {
var url = "http://localhost:4000/api/v2/auth/sign_in";
var payload={email:email,password:password};
axios.post(url,payload)
.then((res)=>{console.log(res)})
.catch((err)=>{alert(err)})
}
export default fetchData;