我在资产管道中有一个带有JavaScript的Rails应用程序。 rails db已保存了URL,我正在尝试使用这些URL /端点对JSON API进行fetch()调用。如果将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
您的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的路径。这是有关相对路径https://stackoverflow.com/a/36369553/632688的更详细的答案。