0

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!!

3 Answers 3

1

You need to specify the Content-Type of data returned from the server.

Either you can use res.setHeader before sending response or res.json() to send json response

https.get(url, (response) => {
    console.log("statusCode", res.statusCode);

    response.on("data", (d) => {
      const weatherData = JSON.parse(d);
      console.log(weatherData);
      res.json(weatherData); // use json response

    });
  }).on("error", (e) => {
    console.error(e);
  })
Sign up to request clarification or add additional context in comments.

Comments

0

It seems there maybe an error occur in result.json().

Probably the request return html rather then json.

You can use postman or other tools to get the real response by 'localhost:3001' to clear where goes wrong.

1 Comment

For some reason the server sending an HTML page instead of the data according to Postman.
0

const data = await result.json();

this line will occur a problem if result does not have valid json. that's why you have encountered an error. catch that error and see the response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.