【问题标题】:304 Error using Netlify Functions in create-react-app在 create-react-app 中使用 Netlify 函数时出现 304 错误
【发布时间】:2021-11-08 11:29:07
【问题描述】:

※发布问题后编辑了一些代码。新代码如下。

我正在尝试使用 Netlify 函数来隐藏我的 API 密钥以获取数据。但是,它返回 304 并且似乎无法正常工作。 以下代码返回错误“SyntaxError: Unexpected token

谁能帮我解决这个问题?

■functions/fetch-weather.js

const handler = async (event) => {
  try {
    const { city } = event.queryStringParameters;
    const API = process.env.REACT_APP_API_KEY;

    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`
    );

    const data = await response.json();
    
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (error) {
    console.log({ statusCode: 500, body: error.toString() });
    return { statusCode: 500, body: error.toString() };
  }
};

module.exports = { handler };

■getCurrentWeather.js

export const getCurrentWeather = async (
  city,
  setLocation,
  setWeather,
  setNotification
) => {
  const fetchWeather = async () => {
    setNotification({ status: 'pending', message: 'Loading...' });

    const response = await fetch(
      `/.netlify/functions/fetch-weather?city=${city}`
    );

    if (!response.ok) {
      throw new Error('cannot get current weather data');
    }

    const data = await response.json();
    return data;
  };

  try {
    const data = await fetchWeather();
    console.log(data);
    setLocation(data.name);
    const [array] = data.weather;
    setWeather(array.main, array.description);
    setNotification({ status: 'success', message: 'Success' });
  } catch (error) {
    console.log(error);
    setNotification({ status: 'error', message: 'Cannot find result' });
  }
};

■netlify.toml

[build]
    functions = "functions"
    publish = "src"

■package.json (运行“npm i netlify-cli --save-dev”)

"devDependencies": {
    "netlify-cli": "^6.8.12"
  }

■控制台图像(使用“netlify dev”打开页面后) error network

【问题讨论】:

    标签: reactjs create-react-app fetch-api netlify netlify-function


    【解决方案1】:

    在您的 netlify 函数发出请求后,您需要使用 .json 来获取 json 数据

    const response = await fetch(
          `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API}`
        );
    
    const data = await response.json();
    

    【讨论】:

    • 在您的 netlify 函数上使用 console.log 打印错误并将其附在此处会有所帮助
    • 感谢您的建议!我在上面添加了错误和网络检查图像。我还添加了几个console.log,但唯一返回的是“SyntaxError: Unexpected token
    • 我说的是 netlify 函数,在 netlify 服务器上运行的代码请参阅此文档docs.netlify.com/functions/logs 尝试查看函数本身的日志,看看函数内部出了什么问题
    猜你喜欢
    • 1970-01-01
    • 2022-08-20
    • 1970-01-01
    • 2019-05-07
    • 2022-01-23
    • 1970-01-01
    • 2018-06-16
    • 2017-10-27
    • 2018-08-23
    相关资源
    最近更新 更多