Строки конечной точки сохранены в rails postgresql db и не могут выполнять вызовы fetch () с ними в js frontend - PullRequest
1 голос
/ 15 марта 2020

У меня есть приложение rails с javascript в конвейере ресурсов. В rails db сохранены URL-адреса, и я пытаюсь выполнить вызовы fetch () с этими URL-адресами / конечными точками для API JSON. Если я поместил URL в адресную строку браузера и удалил кавычки (""), конечная точка вернет данные. Я вижу в консоли ошибку, что URL не существует. Я работаю над localhost: 3000, и это, кажется, добавляется к каждому вызову выборки, как вы можете видеть здесь. Это появится в консоли с ошибкой 404.

http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Seattle,us&APPID=fe2a775f427aa5fc92ce0379937b9ee9 

. Любые предложения о том, как заставить эти вызовы fetch () работать?

Как я могу это реализовать?

Пока что мое приложение будет работать, пока я не нажму совершенные вызовы выборки, а затем верну undefined

const BASE_URL = "http://localhost:3000/cities.json" 
function getCityData(){  
    fetch(BASE_URL).then( res => res.json() ).then(function(json){ 
           //cityArray will be an Array of cities 
           //formatted in a way the api can use
           let cityArray = json.map(obj => obj.name);  
           //cityObjArray will be an array of City objects created 
           // by the class City with city name and api endpoint attributes 
           const cityObjArray = cityArray.map( city => new City(city)); 
           //fetchArray pulls out all the api endpoints from the object
           const fetchArray = cityObjArray.map( cityObj => cityObj.fetchURL);  
           debugger
            let data = fetchArray.map(function(url){   
            // this will work until it hits this point 
            // at this point javaScript will attempt to sanitize the endpoints 
            //and make fetch(url) with them  
            //I will get 404 not found and it will show the endpoint as 
            //starting with localhost:3000 which is were I am running this
                let rawUrl = url.replace(/['"]+/g, ''); 
                debugger
                 fetch(rawUrl).then( res => res.json() ) 
                .then(function(json){
                    debugger
                })
           .catch(function(){
                console.log("ERROR")
            });  
        });
    }) 
}


class City {
    constructor(name){
        this.name = name 
        this.fetchURL = `api.openweathermap.org/data/2.5/weather?q=${name},us&APPID=fe2a775f427aa5fc92ce0379937b9ee9`
    }  

} 


class Adaptor {
    constructor(url){
        this.url = url 
        this.data = fetch(url).then( res => res.json())
    }  

}```


  [1]: https://i.stack.imgur.com/vCS0o.png

1 Ответ

0 голосов
/ 17 марта 2020

Ваши URL должны начинаться с протокола, http://, https:// или // (относительный протокол). В противном случае fetch() интерпретирует их как относительные пути на текущем хосте (localhost: 3000 в вашем примере). Попробуйте это:

this.fetchURL = https://api.openweathermap.org/data/2.5/weather?q=${name},us&APPID=fe2a775f427aa5fc92ce0379937b9ee9 

Это не Rails, который добавляет localhost:3000 к вашим путям. Поскольку вы пропустили протокол, fetch() предполагает, что вы указали ему путь относительно текущего URL. Вот более подробный ответ об относительных путях { ссылка }.

...