Получение ошибки axios при попытке сделать запрос к внешнему API

#javascript #node.js #axios

#javascript #node.js #axios

Вопрос:

Это ошибка: кажется, что ошибка в запросе axios, но я не уверен.. Странно, потому что, когда я тестирую запрос в Postmen, я получаю чистый и красивый ответ.

 UnhandledPromiseRejectionWarning: Error: Request failed with status code 404
    at createError (C:UserslusyvOneDriveDocumentsElevationprojectsweatherAppnode_modulesaxioslibcorecreateError.js:16:15)
    at settle (C:UserslusyvOneDriveDocumentsElevationprojectsweatherAppnode_modulesaxioslibcoresettle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:UserslusyvOneDriveDocumentsElevationprojectsweatherAppnode_modulesaxioslibadaptershttp.js:244:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:13644) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not 
handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:13644) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
  

Я пытаюсь отобразить данные о погоде из внешнего API через localhost server и получаю эту ошибку при нажатии на «кнопку поиска»
Это простая архитектура MVC, вот мой код:

server.js

 router.get(`/city/:cityName`, async (req, res) => {
    let cityName = req.params.cityName
    console.log("LU")
    const response = await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${cityName}amp;units=metricamp;appid=ec035401d1d40d6f5bb07d9588812996`)

    let city = {
        name: response.data.name,
        temprature: response.data.main.temp,
        condition: response.data.weather[0].description,
        conditionPic: response.data.weather[0].icon,  //http://openweathermap.org/img/wn/${icon}@2x.png
        wind: response.data.wind.speed           
    }
    
    res.send(city)
})
  

model.js

 class TempManager {
    constructor(){
        this.cityData = []
    }

    async getDataFromDB(){
        let citiesData = await $.get(`/cities`)

        if(citiesData){
           this.cityData = citiesData
        }

        return(this.cityData)
    }

    async getCityDataFromExtAPI(cityName){
        let city = await $.get(`/city/:${cityName}`)
        console.log(city)
        this.cityData.push(city)

        return(this.cityData)
    }
}
  

controller.js

 let manager = new TempManager()
let renderer = new Renderer()

const loadPage = async () => {
    let citiesDataFromDB = await manager.getDataFromDB()
    renderer.renderData(citiesDataFromDB)
}

const handleSearch = async (userInput) => {
    console.log(userInput)
    let city = await manager.getCityDataFromExtAPI(userInput)
    console.log(city)
    renderer.renderData(city)
}
$(`#search-btn`).on("click", async function () {
    let userInput = $(`#city-input`).val()
    await handleSearch(userInput)
})
  

render.js

 class Renderer {
    constructor(){}

    renderData(allCityData){
        const source = $('#first-template').html()
        const template = Handlebars.compile(source)
        const newHTML = template({city: allCityData})
        $("#city").empty()
        $('#city').append(newHTML)
    }
}
  

index.html

 </head>

    <input type="text" id="city-input">
    <button id="search-btn">Search</button>

<script id="first-template" type="text/x-handlebars-template">
   
    {{#each allCityData}}
    <div id="city">
        <p id="name">{{this.name}}</p>
        <p id="temprature">{{this.temprature}}</p>
        <p id="conditions">{{this.conditions}}</p>
        <img src="{{this.conditionPic}}" alt="condition.jpg" id="image">
        <p id="wind">{{this.wind}}</p>
        <button id="save-btn">Save</button>
        <button id="remove-btn">Remove</button>
    </div>
  {{/each}}
  
  </script>
<body>
  

что я делаю не так?

Комментарии:

1. Код состояния http 404 означает «Не найден». Начните с отладки фактически используемого URL-адреса. Что касается необработанного отклонения обещания, которое требует попытки / перехвата при использовании await .

2. Спасибо! После добавления try / catck отказ от обещания исчез, но я все еще получаю ошибку 404. Я использую Postman для проверки запроса get и получения ответа: «{ «name»: «Лондон», «temprature»: 24.23, «condition»: «чистое небо», «conditionPic»: «01d», «wind»: 4.6 }« на localhost: 3000 /город / Лондон

3. Я только что попробовал в node.js этот запрос axios.get('http://api.openweathermap.org/data/2.5/weather?q=londonamp;units=metricamp;appid=ec035401d1d40d6f5bb07d9588812996') , и он работает просто отлично

4. Итак, что-то изменилось для неудачного. Двоеточие в $.get( /city/:${CityName} ) выглядит очень подозрительно и, вероятно, отображается в req.params.cityName

5. :))))) двоеточие было избыточным! Люблю stackoverflow и его пользователей.