javascript - 获取请求有一个错误,即 api 实际工作时 url 错误
问题描述
我正在尝试向此 api 发出客户端获取请求:'api.openweathermap.org/data/2.5/weather?zip=' 这里我们需要传递 zip+apiKey 来获得响应:
在应用程序中尝试执行此操作,但我在“获取请求”中收到错误,即 url 或获取路由错误:
/* Global Variables */
let baseURL = 'api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = '####';
let appID='&appid=';
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
document.getElementById('generate').addEventListener('click', performAction);
function performAction(e){
const temperature = document.getElementById('zip').value;
const userResponse = document.getElementById('feelings').value;
const getTemp = async (baseURL, temperature, appID,apikey)=>{
const res = await fetch(baseURL+temperature+appID+apikey)
try {
const data=await res.json();
return data;
} catch(error) {
console.log("error", error);
// appropriately handle the error
}
}
getTemp().then( res =>{ console.log(res);
postData('/add', {temperature: temperature, date: newDate, userResponse: userResponse});
updateUI('/all');})
https://codesandbox.io/s/romantic-leaf-0bvpd?file=/src/index.html
解决方案
在这里,您缺少一个“http”协议,因为浏览器会自动添加它。在您的代码中进行以下更改:
let baseURL = 'http://api.openweathermap.org/data/2.5/weather?zip=';
let apiKey = '####';
let appID='&appid='
推荐阅读
- c++ - system("PAUSE) return EXIT_SUCCESS 和 return 0 之间的区别
- react-native - 不可取消的通知 React Native
- azure - 通过 azure 自动化 powershell 禁用/启用 Azure 监视器警报规则
- javascript - Angular 使用从资产文件夹导入
- azure - Azure 应用服务 - 运行自定义可执行文件
- node.js - 在数组中推送数组时 updateOne 和 update 的区别
- android - 我正在使用阿波罗,我无法从响应中获取数据
- c# - 提醒 Facebook Messenger 的聊天机器人
- windows - 当设备已在 Azure AD 中时,无法在 intune 中注册 Windows 10
- yarnpkg - 每个纱线命令都会给出“错误../package.json:名称包含非法字符”