问题
I need to read data from axios response through module.export. This is my data: http://localhost:8001
{
"name":"Nama Nih",
"desc":"Sekolah Terpadu Al-Qudwah - Yayasan Islam Qudwatul Ummah",
"prefix":"alqudwah",
"footerText":"Yayasan Islam Qudwatul Ummah | All Rights Reserved 2020",
"logoText":"Al-Qudwah",
"needLogin":false
}
I call data from axios with this code: brand.js
var axios = require('axios');
module.exports = axios.get('http://localhost:8001', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}})
.then(function (response) {
return response.data;
})
.catch(function (error) {
console.log(error);
})
.then(function () {
});
But when I read response data it's not like expected. I try to console log return value like this:
This is my code where I console.log the response.
import React, { PureComponent } from 'react';
import brand from 'ba-api/brand';
import { Helmet } from 'react-helmet';
class Dashboard extends PureComponent {
render() {
console.log(brand);
const title = brand.name + ' - Dashboard';
const description = brand.desc;
const { classes } = this.props;
return (
<div>
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
</Helmet>
</div>
);
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Dashboard);
How to read this data?
回答1:
Well, you can't export directly the fetched data. Technically you could achieve something similar by:
- performing a sync http request
- wrapping the http function call inside an IIFE
NOTE: The following is not a best-practice approach. In a React component, prefer the suggested
method.
// brand.js
module.exports = (() => {
const request = new XMLHttpRequest();
request.open('GET', 'http://localhost:8001', false);
request.send(null);
if (request.status === 200) {
return request.responseText;
}
})();
Suggested approach
If you can live without having synchronously access to the requested resource, you can wrap axios in a custom hook.
import { useEffect, useState } from 'react';
const useAxios = (url) => {
const [state, setState] = useState({});
useEffect(() => {
axios
.get(url)
.then(({ data }) => setState({ data }))
.catch(error => setState({ error }));
}, []);
return state;
}
// .. in your component
const Component = () => {
const { data, error } = useAxios('http://localhost:8001');
if (error) {
... error component
}
if (!data) {
... loading component
}
return (
... component that is consuming `data`
);
}
In your specific case, as you are using that data only for setting metas, you can skip the error and loading components.
回答2:
I have solved this question with this solution: brand.js
var axios = require('axios');
const sendGetRequest = async () => {
try {
const resp = await axios.get('http://localhost:8001', {
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}})
.then(function (response) {
return response.data;
});
return resp;
} catch (err) {
console.error(err);
}
};
module.exports = sendGetRequest();
And I call that function with this code:
import React, { PureComponent } from 'react';
import brand from 'ba-api/brand';
import { Helmet } from 'react-helmet';
class Dashboard extends PureComponent {
constructor(props){
super(props);
this.state = {
title: '',
description: ''
}
}
componentDidMount(){
brand.then(data => {
this.setState({
title: data.name,
description: data.desc
});
});
}
render() {
const title = this.state.title + ' - Dashboard';
const description = this.state.description;
const { classes } = this.props;
return (
<div>
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
</Helmet>
</div>
);
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Dashboard);
Thank you for all who responses my question.
来源:https://stackoverflow.com/questions/64350949/how-to-read-data-from-axios-response-through-module-exports