我有一个 Rails 应用程序,在 Assets 管道中包含 javascript。 Rails 数据库已保存 url,我正在尝试使用这些 url/端点对 JSON api 进行 fetch() 调用。如果我将 URL 放入浏览器地址栏中并删除引号 (""),端点将返回数据。我可以在控制台中看到该网址不存在的错误。我正在 localhost:3000 上工作,它似乎被附加到每个 fetch 调用中,正如您在此处看到的那样。这将出现在控制台中并显示 404 错误。
http://localhost:3000/api.openweathermap.org/data/2.5/weather?q=Seattle,us&APPID=fe2a775f427aa5fc92ce0379937b9ee9
。关于如何使这些 fetch() 调用正常工作有什么建议吗?
我该如何实现这个?
到目前为止,我的应用程序将一直运行,直到我执行了提取调用,然后返回未定义
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]: /image/vCS0o.png
最佳答案
您的网址需要以协议(protocol)开头,http://
、https://
或 //
(相对协议(protocol))。否则,fetch()
将它们解释为当前主机的相对路径(在示例中为 localhost:3000)。试试这个:
this.fetchURL = https://api.openweathermap.org/data/2.5/weather?q=${name},us&APPID=fe2a775f427aa5fc92ce0379937b9ee9
Rails 并未将 localhost:3000
添加到您的路径中。由于您省略了协议(protocol),因此 fetch()
假定您已为其指定了相对于当前 URL 的路径。这是关于相对路径的更详细答案https://stackoverflow.com/a/36369553/632688 .
关于javascript - 端点字符串保存在rails postgresql db中,无法在js前端中使用它们进行fetch()调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60690356/