首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >304在create-react-app中使用Netlify函数时出错

304在create-react-app中使用Netlify函数时出错
EN

Stack Overflow用户
提问于 2021-09-13 06:24:18
回答 1查看 108关注 0票数 0

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

我正在尝试使用Netlify函数来隐藏我的API密钥来获取数据。但是,它返回一个304,并且似乎不起作用。下面的代码返回错误"SyntaxError: Unexpected < in JSON at position 0“,响应代码为304。

有人能帮我改进一下吗?

函数/fetch-weather.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
[build]
    functions = "functions"
    publish = "src"

Package.json(运行"npm i netlify-cli --save-dev")

代码语言:javascript
复制
"devDependencies": {
    "netlify-cli": "^6.8.12"
  }

控制台镜像(在打开带有"netlify dev“的页面后) error network

EN

回答 1

Stack Overflow用户

发布于 2021-09-13 06:32:11

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

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

const data = await response.json();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69158145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档