当我连接到天气 api 时,url 传递错误

Error in the url passed when I connect to a weather api

这是我的第一个使用 node.js 和 express 的应用程序。这是一个基本的应用程序,我连接到外部 API 以显示温度并获取用户输入“城市和感觉”并将其显示给 UI。我无法正确输入 URL。不知道为什么。

我运行应用程序并在城市和感觉文本区域输入数据,我调试了app.js文件,发现当它试图获取URL时,我传递它的数据会给出错误“400 个错误的请求”。我做错了什么?

server.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)
}

website/app.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);
  }
}

website/index.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>

你的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 参数。

但是,如果您将 url 中的 city 参数更改为 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}