Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - Issue with getting data from OpenWeatherMap API

I am building a fullstack weather app in vanilla javascript on the frontend and Node.js with Express and Axios on the backend.

On the frontend I am using fetch() to sent a POST request to the backend. The API is in the backend and I can get the data from the API back to the frontend only if I hard code the query(i.e: 'q=London').

My guess is that I am not sending the correct info in the 'body: JSON.stringify()' inside the fetch() method.

Please have a look at the code samples bellow and hopefully will be able to point me to the solution.

Thank you in advance!

Here is the server side code sample: 

  app.post('/test', (req, res) => {

      const url = `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${apiKey}&units=metric`;

      axios({
        url:url,
        responseType: 'json',
     })
      .then(data => {
      res.json(data.data)
   })

})


Here is the frontend code sample:

const fetchData = () => {
  fetch('/test',{
    method: 'POST',
      headers: {
        "Content-Type": "application/json",
        "Accept": "application/json"
      },
      body: JSON.stringify({
        data: cityName
    
      })
  })
  .then(res => res.json())
  .then(data =>{
    console.log('data received: ', data)
}
question from:https://stackoverflow.com/questions/65905137/issue-with-getting-data-from-openweathermap-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...