![](/img/trans.png)
[英]XMLHttpRequest cannot load https://localhost:8585/pay due to access control checks
[英]How to fix 'Fetch API cannot load http://localhost:3000/static/js/0.chunk.js due to access control checks'
我正在使用 React 構建一個通用的天氣網絡應用程序。 現在我只是想獲取一個城市的天氣數據(即還沒有做任何動態的事情)並將其記錄在控制台中。
我正在使用 OpenWeatherMap API。
但是,每當我調用 API 時,我都會收到以下錯誤:
以前,我曾嘗試使用 AccuWeather API,但它給出了相同的錯誤。
但是,如果我在 React 的 componentDidMount() 函數中調用 API,它會很好地獲取數據。 當我嘗試在表單提交時獲取天氣數據時出現問題。
這是我的主要應用程序代碼:
weatherData = async function() {
try {
const resp = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=APP-ID');
const data = await resp.json();
console.log(data);
} catch (err) {
console.log(err)
}
}
render() {
return (
<div>
<Title />
<Form loadWeather={this.weatherData} />
</div>
)
}
}
這是 React 組件:
import React from 'react';
import './Form.css';
const Form = (props) => {
return (
<form onSubmit = {props.loadWeather}>
<input className='input' type='text' name='city' placeholder='Enter City'></input>
<input className='input' type='text' name='country' placeholder='Enter Country'></input>
<button className='button'>Get Weather!</button>
</form>
)
}
您需要將 weatherData 綁定到父組件才能在子組件中執行。 為此,只需將其綁定到第一個組件的構造函數即可:
this.weatherData = this.weatherData.bind(this)
作為:
constructor(props) {
super(props)
this.state = {
//blabla
},
this.weatherData = this.weatherData.bind(this)
}
您需要完全采用一種方法或使用另一種方法:
基本 React.Component 類示例:
constructor(props) {
//...
this.weatherData = this.weatherData.bind(this);
}
async weatherData() {/* your code */}
或者,使用鎮靜方法:
weatherData = () => {/* ... */}
您的鎮定正在分配一個重新綁定this
上下文的function()
。 你需要指定一個箭頭函數() => {}
保存this
為找不到自己得到this
失落。
解決這種綁定問題的最佳方法是使用函數式方法:
function WeatherThing() {
const weatherData = async () => {
const weatherInfo = await weatherDataFetch();
}
return (<div onClick={weatherData}>Do Weather stuff</div>);
}
我建議閱讀React Hooks以使您的代碼更具可讀性。
我更改了我的開發環境的主機名並遇到了同樣的問題。
如果您重新啟動瀏覽器或機器,問題應該會消失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.