Error 400 when parameter in API request is set as a State in React

huangapple go评论68阅读模式
英文:

Error 400 when parameter in API request is set as a State in React

问题

这是一个获取位置天气详情的GET请求。以下是我的代码示例:

const [weather, setWeather] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [location, newLocation] = useState("Mumbai");

const locationHandler = (place) => {
  newLocation(place);
};

const fetchWeatherHandler = useCallback(async () => {
  setIsLoading(true);
  setError(null);
  try {
    console.log(location);
    const response = await fetch(
      `http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${location}&aqi=yes`
    );

    if (!response.ok) {
      throw new Error("Something went wrong!");
    }

    const data = await response.json();
    console.log(data);
    setWeather(data);
  } catch (error) {
    setError(error.message);
  }
  setIsLoading(false);
  weather && console.log(weather);
}, []);

useEffect(() => {
  fetchWeatherHandler();
}, [fetchWeatherHandler]);

在GET请求中,q="Mumbai"返回200状态代码,但当用${{location}}替代以便根据用户输入显示天气时,返回400状态代码。

我似乎无法理解为什么会这样。

英文:

This is a get request to get weather details of a location. Here's what my code looks like:

const [weather, setWeather] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [location, newLocation] = useState(&quot;Mumbai&quot;);

const locationHandler = (place) =&gt; {
newLocation(place);
};

const fetchweatherHandler = useCallback(async () =&gt; {
setIsLoading(true);
setError(null);
try {
  console.log(location);
  const response = await fetch(
    `http://api.weatherapi.com/v1/current.json?key=&lt;api_key&gt;&amp;q=${{
      location,
    }}&amp;aqi=yes`
  );

  if (!response.ok) {
    throw new Error(&quot;Something went wrong!&quot;);
  }

  const data = await response.json();
  console.log(data);
  setWeather(data);
} catch (error) {
  setError(error.message);
}
setIsLoading(false);
weather &amp;&amp; console.log(weather);
}, []);

 useEffect(() =&gt; {
fetchweatherHandler();
}, [fetchweatherHandler]);

In the get request q=&quot;Mumbai&quot; yields 200 status code but when replaced with ${{location}} so that weather can be displayed in terms of user input, yields a 400 status code.

I can't seem to understand why is this so.

答案1

得分: 0

为什么你在模板字符串中使用了两次花括号?这会创建一个对象,这不是你想要的输出:

const test = "Mumbai";
console.log(`http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${{test}}&aqi=yes`);

(你可以通过在调试中输出结果值或观察浏览器调试工具中的请求URL来观察这一点。)

只需要使用一组花括号来评估字符串值:

const test = "Mumbai";
console.log(`http://api.weatherapi.com/v1/current.json?key=<api_key>&q=${test}&aqi=yes`);
英文:

Why are you doubling the curly braces in the template string? That creates an object, which isn't the output you want:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const test = &quot;Mumbai&quot;;
console.log(`http://api.weatherapi.com/v1/current.json?key=&lt;api_key&gt;&amp;q=${{test}}&amp;aqi=yes`);

<!-- end snippet -->

(You can, and should, observe this in your debugging by simply outputting the resulting value, or by observing the URL of the request in your browser's debugging tools.)

Just use one set of curly braces to evalutate the string value:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const test = &quot;Mumbai&quot;;
console.log(`http://api.weatherapi.com/v1/current.json?key=&lt;api_key&gt;&amp;q=${test}&amp;aqi=yes`);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月9日 01:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定