I'm new to node and react and I am trying to fetch some data and show it on my react page. It's pretty simple. I have an express server running on localhost:3001 and my react app is on localhost:3000. I'm attempting to fetch data and then set that data to a state via a hook. I can't seem to get the data on the react page or in the web developer console. Is there a way I can see the data that is being fetched in the console?
Here is my React component:
import React, { useState } from "react";
function App() {
const [weatherData, setWeatherData] = useState("");
console.log(weatherData);
React.useEffect(() => {
const fetchData = async () => {
const result = await fetch(
"http://localhost:3001"
);
const data = await result.json();
console.log("data", data);
setWeatherData(data);
};
fetchData();
})
return (
<div>
<h1>The temprature is {weatherData}</h1>
</div>
);
}
export default App;
Here is my node server:
const express = require('express');
const bodyParser = require('body-parser');
const https = require("https");
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'jsx')
app.use(express.static("public"));
app.get("/", function (req, res) {
const query = Chicago;
const apiKey = "a valid key";
const unit = "imperial";
const url = "https://api.openweathermap.org/data/2.5/weather?appid=" + apiKey + "&q=" + query + "&units=" + unit;
https.get(url, (response) => {
console.log("statusCode", res.statusCode);
response.on("data", (d) => {
const weatherData = (JSON.parse(d));
console.log(weatherData);
res.send(weatherData);
});
}).on("error", (e) => {
console.error(e);
})
});
const port = process.env.PORT || 3001;
app.listen(port, () => console.log(`Listening on port ${port}`));
The result I get is no data and these 2 errors in chrome dev tools console.
index.js:1 Uncaught SyntaxError: Unexpected token '<'
App.jsx:19 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Any help is greatly appreciated!!