Ошибка в URL прошла при подключении к API погоды - PullRequest
1 голос
/ 14 марта 2020

Это мое первое приложение, которое делает это с node.js и express. Это базовое c приложение, в котором я подключаюсь к внешнему API, чтобы показать температуру, а также ввожу пользовательский ввод "город и ощущение" и показываю его в пользовательском интерфейсе. Я не могу правильно понять URL. Я не знаю, почему.

enter image description here

Я запустил приложение и ввел данные в городе и в текстовой области ощущения, я отладил приложение. js файл и обнаружил, что когда он пытается получить URL, я передаю свои данные, он выдает ошибку «400 неверных запросов». Я ценю вашу помощь в сообщении, что я делаю неправильно.

сервер. js

// Setup empty JS object to act as endpoint for all routes
projectData = {};



// Require Express to run server and routes
const express = require('express');

// Start up an instance of app
const app = express();
/* Middleware*/
//body-parser as the middle ware to the express to handle HTTP POST
const bodyParser = require('body-parser');
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder , this line allows talking between server and client side
app.use(express.static('website'));


// Setup Server
const port = 8000;
const server = app.listen(port , ()=>{console.log(`the server running on localhost: ${port}`);}); 


//GET function
app.get('/fakeData' , getFakeData);  //string represents a url path >> /  means home 
function getFakeData (req,res) {
    // body...
    console.log(projectData);
    res.send(projectData);
}


var project = [];

app.get('/all', sendData);

function sendData (request, response) {
  response.send(project);
  console.log(project);
};


//POST function
app.post('/addAnimal' ,addAnimal);
function addAnimal (req,res) {
    // body...
    newEntry = {
        date: req.body.date,
        temp: req.body.main.temp,
        feeling: req.body.feeling
    }

    project.push(newEntry)
    res.send(project)
    console.log(project)
}

веб-сайт / приложение. js

/* Global Variables */
//let baseURL = 'http://api.openweathermap.org/data/2.5/weather?q=Egypt&APPID=';
let baseURL = `http://api.openweathermap.org/data/2.5/weather?city=`;
let apiKey = '&APPID=bb95e29dbedc4d929be90b0dd99954e0';

// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();




//GET request to handle user input 
document.getElementById('generate').addEventListener('click', performAction);

function performAction(e){
//Take user input
//const zipcode = document.getElementById('zip').value;  //no
const feeling = document.getElementById('feelings').value;
const city = document.getElementById('zip').value;

//the fake api call
//getAnimal('/fakeAnimalData')
getTemp(baseURL ,city , apiKey )
.then (function(data) {
    // body...
    console.log(data)
    postData('/addAnimal' ,{temp:data.main.temp ,date:newDate, feeling:feeling} )
    //updateUI()
})
.then(
    updateUI()
  )

};


 const getTemp = async(baseURL ,city , apiKey)=>{
    const res = await fetch(baseURL+city+apiKey)
    try{
        const data = await res.json();
        console.log(data)
        return data;
    }
    catch(error){
        console.log("error" , error);
    }
}


//make a POST request to our route , POST to store locally user-input data 
const postData = async(url='' , data={})=>{
    //console.log(data);
    const response = await fetch(url , {
      method: 'POST', 
      credentials: 'same-origin',
      headers: {
          'Content-Type': 'application/json',
      },
      // Body data type must match "Content-Type" header        
      body: JSON.stringify(data), 
    });

    try {
        const newData = await response.json();
        console.log(newData);
        return newData
    }catch(error){
      console.log("error", error);
  }
}





const updateUI = async () => {
  const request = await fetch('/all');
  try{
    const allData = await request.json()
    console.log(allData);
    document.getElementById('date').innerHTML = allData[0].date;
    document.getElementById('temp').innerHTML = allData[0].temp;
    document.getElementById('content').innerHTML = allData[0].feeling;

  }catch(error){
    console.log("error", error);
  }
}

веб-сайт / индекс. js

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
<link href="https://fonts.googleapis.com/css?family=Oswald:400,600,700|Ranga:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
 <body>
<div id = "app">
  <div class ="holder headline">
    Weather Journal App
  </div>
  <div class ="holder zip">
    <label for="zip">Enter Zipcode here</label>
    <input type="text" id="zip" placeholder="enter zip code here">
  </div>
  <div class ="holder feel">
    <label for="feelings">How are you feeling today?</label>
    <textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="9" cols="50"></textarea>
    <button id="generate" type = "submit"> Generate </button>
  </div>
  <div class ="holder entry">
    <div class = "title">Most Recent Entry</div>
   <div id = "entryHolder">
    <div id = "date"></div> 
   <div id = "temp"></div>
   <div id = "content"></div>
  </div>
  </div>
  </div>
<script src="app.js" type="text/javascript"></script>

</body>
</html>

1 Ответ

1 голос
/ 14 марта 2020

Кажется, нет проблем в создании вашего URL. Я открыл http://api.openweathermap.org/data/2.5/weather?city=cairo&APPID=bb95e29dbedc4d929be90b0dd99954e0 в браузере и возвращает HTTP 400 Bad Request в качестве кода состояния, и из-за кода состояния 400 браузер сообщает, что запрос не выполнен.

Вот ответ , {"cod":"400","message":"Nothing to geocode"}

Кажется, исходная проблема - это ваш city параметр, который вы отправляете.

Однако, если вы измените параметр city в вашем URL на q, он похоже на работу. http://api.openweathermap.org/data/2.5/weather?q=cairo&appid=bb95e29dbedc4d929be90b0dd99954e0

Вот ответ. {"coord":{"lon":31.25,"lat":30.06},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":295,"feels_like":293.65,"temp_min":294.82,"temp_max":295.15,"pressure":1015,"humidity":64},"visibility":10000,"wind":{"speed":4.1,"deg":290},"clouds":{"all":75},"dt":1584185538,"sys":{"type":1,"id":2514,"country":"EG","sunrise":1584158752,"sunset":1584201751},"timezone":7200,"id":360630,"name":"Cairo","cod":200}

...