I am trying to fetch API by using axios get method. This is the link http://open-api.myhelsinki.fi/v1/events/?language_filter=en.
My backend is Node js with Express and frontend is React js. It's working fine when I run in Postman and also Express server (It shows the data). But When I render it in React component, it does not show anything.
When I checked the React component's network status, it shows pending. I don't know, What I am doing wrong since I don't get any error.
This is my Express server setup
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
const cors = require("cors");
const axios = require("axios");
app.use(cors());
app.get("/events", async (req, res, next) => {
axios
.get("http://open-api.myhelsinki.fi/v1/events/?language_filter=en")
.then(response => console.log(response))
.catch(err => console.log(err));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Server's package.json file
{
"name": "myhelsinki",
"version": "1.0.0",
"description": "This is for educational purpose",
"main": "index.js",
"scripts": {
"start": "node server.js",
"server": "node server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "alak",
"license": "ISC",
"dependencies": {
"axios": "^0.19.1",
"concurrently": "^5.0.2",
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
This is my React component.
import React, { useEffect } from "react";
import axios from "axios";
const Events = () => {
useEffect(() => {
events();
}, []);
const [state, setstate] = React.useState([]);
const events = () => {
axios
.get("http://localhost:5000/events")
.then(res => res.json())
.then(response => setstate(response.data))
.catch(err => console.log(err));
};
return (
<div>
{state.map(list => {
return <li>{list.id}</li>;
})}
</div>
);
};
export default Events;
This is React's package.json file. Ps. I have tried proxy settings in package.json but it did not work as well.
{
"name": "myhelsinki",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}