DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL in react - reactjs

Suhu/Guru, help me
componentDidMount() {
axios
.get(API_URL + "products")
.then((res) => {
const menus = res.data;
this.setState({ menus });
})
.catch((error) => {
console.log(error);
});
}
render() {
console.log(this.state.menus);
return (
and my API in Local Server
export const API_URL = "http://localhost:3004";
and thi's my problem
enter image description here

Your result URL is "http://localhost:3004products" you must to append '/' after API_URL

May be It is making request as "http://localhost:3004products", add '/' in-between URL.
Either add '/' before product or behind URL of API_URL
componentDidMount() {
axios
.get(API_URL + "/products") // Change
.then((res) => {
const menus = res.data;
this.setState({ menus });
})
.catch((error) => {
console.log(error);
});

Related

Fetching data using API in react.js

I am trying to fetch data using API in react.js. My code is like below
import Axios from 'axios';
export const getCountry = () => dispatch => {
return Axios.get('http://treeoverflow.com/api/country/listing/true/111111111111222222222222333333333333444444444444', { crossdomain: true })
.then(response => {
console.log(response.data);
var countryData = response.data;
dispatch({
type: 'getCountries',
payload: countryData
});
})
.catch(function(error) {
console.log('hello');
dispatch({
type: 'getCountryError',
payload: error
});
});
};
export default { getCountry };
I getting below view in Network tab.
But I am not getting result. Is there any issue in this URL 'http://treeoverflow.com/api/country/listing/true/111111111111222222222222333333333333444444444444' ?

How to save single object into state, from json end point axios

UPDATE:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
this.setState({profile: response.data})
})
^ saved the object in state for me :) Thanks everyone!!
I am a newbie to react. I am trying to save a single object from a JSON end point into the state of my react component. I am definitely returning the JSON data in the response. However it is not being saved into the state, can you see where I am going wrong?
// State needed for the component
constructor(props) {
super(props);
this.state = {
profile: {},
};
}
// Grabs profile data from the json url
private getProfile() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data(profile => ({
id: `${ profile.id }`
}))
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
JOSN data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
Your first then block looks wrong.
Try to do console.log there like this:
.then(response => {
console.log(response); // I am sure that you will get profile inside response.data or something similar
return response.data(profile => ({
id: `${ profile.id }`
}));
})
If you want to keep your first then that "prepares the data", then you should return a promise instead of data, like:
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWV....'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {
return new Promise((resolve, reject) => {
resolve( {
id: `${ response.data.id }`
});
});
}
)
.then(profile => {
this.setState({
profile
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
Here's an example of how that would work:
I do believe that's a bit of an overkill though and you should be able to just set your state in the first then such as:
this.setState({profile: {id : response.data.id}});
Try to remove the second then, like this:
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => {this.setState({ profile: response.data })};
})
}))

Initial fetch get request slow using React, Express

In a simple react set up with express, the very first fetch get request is too slow. The get requests following it seem normal speed.See the first /api/passages/happiness in the log below with a time of 33+ milliseconds.
Basic order of operations:
button click triggers GET request from local Express server
sets state with the data
calls an external API through a proxy url
displays that data in a modal
I'm new at speed/performance issues. Where do I begin troubleshooting? Or which step is likely slowing it down?
// onClick of button, these steps occur:
handleOpen = () => {
// 1. call express api, returns a few lines of text
baseService.get(`/api/passages/${this.props.document}`)
.then(data => {
this.setState({
reference: data.reference,
abbr: data.abbr,
start: data.start,
end: data.end
})
})
.catch(err => {
alert("Verse failed to load")
console.log(err)
})
// 2. call external api, returns a few lines of text
.then(() => {
const url = `https://bibles.org/v2/chapters/eng-NASB:${this.state.abbr}/verses.js?start=${this.state.start}&end=${this.state.end}`
fetch(proxyurl + url, {
headers: new Headers({ 'Authorization': 'Basic ' + window.btoa(`${BIBLE_API_KEY}: x`) }),
redirect: "follow",
})
.then(res => res.json())
.then(contents => {
let versearray = contents.response.verses
versearray.forEach(verse => {
var regex = /(<([^>]+)>)|[0-9]/ig;
let versetext = verse.text.replace(regex, "");
let alltext = this.state.content.concat(' ', versetext)
this.setState({
content: alltext,
// 3. open modal displaying few lines of text
open: true
})
})
})
})
.catch(err => {
alert("Your Verse Failed to Load");
console.log(err)
})
};
config
let mongoose = require('mongoose');
const server = '127.0.0.1:27017'
const database = 'verseapp';
class Database {
constructor() {
this._connect()
}
_connect() {
mongoose.connect(`mongodb://${server}/${database}`, {
useNewUrlParser: true,
useCreateIndex: true,
})
.then(() => {
console.log('Database connection successful')
})
.catch(err => {
console.log('Database connection error', err)
})
}
}
module.exports = new Database()

How to update the page after call Axios Successful ? React

so I'm doing a project that uses Axios with Json-server, but I have a problem, every time I do a Patch, I have to give F5 on the homepage for it to update, I wanted know how I could do it so that it did not happen, and automatically.
My Patch:
onSubmitDate = event => {
const newUrl = prompt("Please with new URL:");
const personCurrent = event.target.value;
axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
url_git: newUrl
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
My Get:
componentDidMount() {
axios
.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
}
Someone would can help me?
I am assuming the update is on the component you are handling.
For you to create a re-render of your component, you can simply set the state. See more here
What is the format of your response? Does it include the updated data you wish to display? If that is the case, it's easy, simply do a setState in your then:
onSubmitDate = event => {
const newUrl = prompt("Please with new URL:");
const personCurrent = event.target.value;
axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
url_git: newUrl
})
.then(response => {
console.log(response);
this.setState({employee: response.data})
})
.catch(error => {
console.log(error);
});
}
If the response is not providing the data you want updated in your component, your can simply do your GET of whatever data you want in the then of your PATCH and set the state on it's response. So something like this:
onSubmitDate = event => {
const newUrl = prompt("Please with new URL:");
const personCurrent = event.target.value;
axios.patch(`http://localhost:3004/employee/${personCurrent}`, {
url_git: newUrl
})
.then(response => {
console.log(response);
axios.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
})
.catch(error => {
console.log(error);
});
}

React Native - Undefined is not an object when evaluating promise

i am beginner react-native programmer . I am trying to return the responseJSON in a fetch function . I know it is asynchronous and will return promise, thus I need to use .then() , but when it says undefined is not an object.
here is the code
auth.js
export const onVerify = (email,password,navigation) => {
console.log('Verifying');
fetch('xxx',
{
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'email=' + email + '&password=' + password
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
return responseJson
}
in my signin.js
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
);
}
As said by #teivaz on the comment, your onVerify function returns nothing. Because the fetch call is asynchronous. So what you can do is return a Promise from onVerify then you'll be able to resolve it from step function.
This is how you can implement this,
export const onVerify = (email,password,navigation) => {
return new Promise((resolve, reject) => {
fetch('endpoint',
{
method,
headers,
body,
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status == '200') {
Alert.alert(
'Login Successful',
'Welcome Home'
);
let data = {
name: responseJson.name,
id : responseJson.id
};
onSignIn();
resolve(responseJson)
}
})
.catch(err => reject(err));
}
}
Also, make sure to catch the errors if any in step function.
export default class SignIn extends React.Component{
step(){
onVerify(this.state.email,this.state.password,this.props.navigation).then(
function(data) {
console.log(data);
}
)
.catch(err => console.log('Error occured', err));
}
}

Resources