后端前端Web框架开发工具【免费下载链接】redwoodRedwoodGraphQL项目地址https://gitcode.com/gh_mirrors/re/redwood点击查看免费下载本文基于 Redwood v6 官方文档 Using a Third Party API 展开。Redwood 是一个全栈 JS 框架前端web基于 React后端api自带 GraphQL 服务层二者天然打通。当应用需要从外部服务获取数据时可以选择在浏览器端直接调用第三方 API也可以让 Redwood 的 serverless 函数代为请求再通过自家 GraphQL 接口暴露给前端。本文将以构建一个「输入美国邮编、显示当前天气」的小应用为例完整演示两种集成路径并深入结合仓库源码讲解 SDL、Service、Cell、表单校验与错误处理背后的实现机制。读完本文你将掌握在 Redwood 应用中安全、规范地集成任意第三方 HTTP API 的完整套路。场景与准备工作我们将构建一个简单的天气应用用户输入一个美国邮编zip code页面展示该地区当前的天气状况。为此需要从 OpenWeather 获取实时天气数据。1. 注册 OpenWeather 并获取 API Key在 OpenWeather 官网创建一个免费账户并验证邮箱进入 API keys 页面复制默认生成的 API Key免费账户每天可调用 1,000 次足够示例应用使用。注意新注册的 Key 可能需要等待最长 30 分钟才会被激活。等待期间可以使用 OpenWeather 提供的示例响应端点来预览数据结构。2. 理解 OpenWeather 的响应结构调用https://api.openweathermap.org/data/2.5/weather?zip94040,usappidYOUR_API_KEY返回的标准 JSON 结构如下示例数据城市为 Mountain View{ coord: { lon: -122.09, lat: 37.39 }, weather: [ { id: 500, main: Rain, description: light rain, icon: 10d } ], base: stations, main: { temp: 280.44, pressure: 1017, humidity: 61, temp_min: 279.15, temp_max: 281.15 }, visibility: 12874, wind: { speed: 8.2, deg: 340, gust: 11.3 }, clouds: { all: 1 }, dt: 1519061700, sys: { type: 1, id: 392, country: US, sunrise: 1519051894, sunset: 1519091585 }, id: 0, name: Mountain View, cod: 200 }对页面展示有用的字段包括name邮编对应的城市名main.temp当前温度单位为开尔文 Kelvin需要转换为华氏度或摄氏度weather[0].main英文天气状况描述如 Rainweather[0].icon天气图标代码可拼接为图标 URLhttps://openweathermap.org/img/wn/{icon}2x.png。创建 Redwood 应用与首页表单与创建其他 Redwood 应用完全一致yarn create redwood-app weatherstation cd weatherstation yarn rw dev浏览器会自动打开http://localhost:8910。接着生成首页路由与页面yarn rw generate page home /也可以用完整命令yarn redwood generate page home /。生成后首页位于web/src/pages/HomePage/HomePage.js。现在为首页添加一个输入邮编的表单。Redwood 提供了redwoodjs/forms表单库底层是对react-hook-form的封装见仓库 packages/forms/src/Form.tsx其中Form组件通过useFormFormProvider建立表单上下文因此可以享受声明式的校验能力import { Form, TextField, Submit } from redwoodjs/forms const HomePage () { const onSubmit (data) { console.info(data) } return ( Form onSubmit{onSubmit} style{{fontSize: 2rem}} TextField namezip placeholderZip code maxLength5 validation{{ required: true, pattern: /^\d{5}$/ }} / SubmitGo/Submit /Form ) } export default HomePagevalidation对象中的pattern: /^\d{5}$/会在提交时校验输入必须是 5 位纯数字。Redwood 的 forms 包还会根据字段名、required、emptyAs等条件自动做值类型转换coercion相关逻辑可见 packages/forms/src/coercion.ts。在浏览器开发者工具中点击Go即可在控制台看到提交的{ zip: 94040 }数据。接下来我们需要真正调用 API。Redwood 提供了两条路径客户端集成由浏览器中的 React 应用直接调用第三方 API服务端集成由 Redwood 的服务端serverless function / GraphQL Service调用第三方 API客户端只与自家 GraphQL 接口通信。下面分别展开。客户端集成浏览器直连第三方 API方案取舍优点设计最简单无需搭建任何服务端逻辑网络请求最少客户端一次请求直达第三方速度快无中间层转发。缺点不安全用户查看页面源码即可拿到 API Key无法限流恶意脚本可以每秒成千上万次地轰炸该页面。真实项目中需要结合风险权衡选择。使用 Fetch 拉取数据表单的onSubmit已经拿到了邮编直接在回调中调用浏览器内置的 Fetch APIconst onSubmit (data) { fetch( https://api.openweathermap.org/data/2.5/weather?zip${data.zip},usappidYOUR_API_KEY ) .then((response) response.json()) .then((json) console.info(json)) }如果 API Key 尚未激活不要尝试把 URL 换成示例响应端点——跨域CORS会导致请求失败只能等待 Key 生效。用 React state 渲染天气引入useState保存 API 结果并触发界面刷新注意表单和输出需要包裹在 /片段中import { useState } from react import { Form, TextField, Submit } from redwoodjs/forms const HomePage () { const [weather, setWeather] useState() const onSubmit (data) { fetch( https://api.openweathermap.org/data/2.5/weather?zip${data.zip},usappidYOUR_API_KEY ) .then((response) response.json()) .then((json) setWeather(json)) } return ( Form onSubmit{onSubmit} TextField namezip placeholderZip code maxLength5 validation{{ required: true, pattern: /^\d{5}$/ }} / SubmitGo/Submit /Form {weather JSON.stringify(weather)} / ) } export default HomePage格式化并展示真实天气最后补充辅助函数将开尔文转为华氏度、提取天气状况、拼装图标 URL然后渲染到页面上import { useState } from react import { Form, TextField, Submit } from redwoodjs/forms const HomePage () { const [weather, setWeather] useState() const onSubmit (data) { fetch( https://api.openweathermap.org/data/2.5/weather?zip${data.zip},usappidYOUR_API_KEY ) .then((response) response.json()) .then((json) setWeather(json)) } const temp () Math.round(((weather.main.temp - 273.15) * 9) / 5 32) const condition () weather.weather[0].main const icon () { return https://openweathermap.org/img/wn/${weather.weather[0].icon}2x.png } return ( Form onSubmit{onSubmit} TextField namezip placeholderZip code maxLength5 validation{{ required: true, pattern: /^\d{5}$/ }} / SubmitGo/Submit /Form {weather ( section h1{weather.name}/h1 h2 img src{icon()} style{{ maxWidth: 2rem }} / span {temp()}°F and {condition()} /span /h2 /section )} / ) } export default HomePage功能已经跑通。但正如前文所述把 API Key 暴露在浏览器端存在明显安全风险接下来看更稳妥的服务端方案。服务端集成通过 Redwood GraphQL 代理第三方 API服务端方案要做两件事为客户端提供访问自家服务端serverless function的接口让服务端去访问第三方 API。Redwood 内置 GraphQL 集成因此使用 GraphQL SDL 定义面向客户端的接口用 Service 实现调用第三方 API 的业务逻辑。为什么不用 SDL 生成器Redwood 的yarn rw g sdl生成器默认假设你在api/db/schema.prisma中定义了数据模型生成的 SDL 面向的是数据库表结构。当需要自定义一个与数据库无关的 API 接口时需要手写 SDL。定义 GraphQL SDL我们可以自定义返回的数据结构把 OpenWeather 响应中无关的字段剔除只保留客户端需要的部分甚至可以在服务端提前完成单位转换与图标 URL 拼装export const schema gql type Weather { zip: String! city: String! conditions: String! temp: Int! icon: String! } type Query { getWeather(zip: String!): Weather! skipAuth } 说明zip定义为String!而非Int因为邮编可能以0开头skipAuth指令表示该查询无需登录即可访问。Redwood 通过createValidatorDirective机制将 SDL 中的指令与校验函数绑定见 packages/graphql-server/src/directives/makeDirectives.ts默认生成的requireAuth用于鉴权场景。编写 ServiceGraphQL 解析器在 Redwood 中GraphQL Query 类型会自动映射到同名 Service 中导出的同名函数。因此创建api/src/services/weather/weather.js导出getWeather。先用假数据验证整个链路export const getWeather ({ zip }) { return { zip, city: City, conditions: Hot Lava, temp: 1000, icon: https://placekitten.com/100/100, } }Redwood 自带 GraphQL PlaygroundGraphiQL在浏览器打开http://localhost:8911/graphql左上输入查询、左下输入变量点击 Play 即可验证query GetWeatherQuery($zip: String!) { getWeather(zip: $zip) { zip city conditions temp icon } }变量{ zip: 94040 }。接入真实的 OpenWeather 请求服务端环境没有浏览器内置的fetch需要安装一个符合 Fetch API 规范的包yarn workspace api add whatwg-node/fetch然后改造 Service。fetch返回 Promise用async/await简化异步逻辑import { fetch } from whatwg-node/fetch export const getWeather async ({ zip }) { const response await fetch( https://api.openweathermap.org/data/2.5/weather?zip${zip},USappidYOUR_API_KEY ) const json await response.json() return { zip, city: json.name, conditions: json.weather[0].main, temp: Math.round(((json.main.temp - 273.15) * 9) / 5 32), icon: https://openweathermap.org/img/wn/${json.weather[0].icon}2x.png } }再次在 GraphQL Playground 点击 Play即可看到来自 OpenWeather 的真实数据。与客户端方案相比API Key 完全保留在服务端不向浏览器暴露。用 Cell 在客户端展示天气Redwood Cell 封装了查询、加载、空态、失败、成功等全部状态渲染逻辑是消费自家 GraphQL 接口的标准方式。先用生成器创建 Cell 骨架yarn rw generate cell weather生成web/src/components/WeatherCell/WeatherCell.js初始内容为export const QUERY gql query FindWeatherQuery($id: Int!) { weather: weather(id: $id) { id } } export const Loading () divLoading.../div export const Empty () divEmpty/div export const Failure ({ error }) ( div style{{ color: red }}Error: {error.message}/div ) export const Success ({ weather }) { return div{JSON.stringify(weather)}/div }把QUERY改为匹配我们自定义的 API 签名export const QUERY gql query GetWeatherQuery($zip: String!) { weather: getWeather(zip: $zip) { zip city conditions temp icon } } 注意weather: getWeather的别名用法实际调用的是getWeather端点但返回结果会被重命名为weather并作为Success组件的 props 传入。在HomePage中使用该 Cell并引入 state 记录用户何时提交了邮编import { Form, TextField, Submit } from redwoodjs/forms import { useState } from react import WeatherCell from src/components/WeatherCell const HomePage () { const [zip, setZip] useState() const onSubmit (data) { setZip(data.zip) } return ( Form onSubmit{onSubmit} style{{ fontSize: 2rem }} TextField namezip placeholderZip code maxLength5 validation{{ required: true, pattern: /^\d{5}$/ }} / SubmitGo/Submit /Form {zip WeatherCell zip{zip} /} / ) } export default HomePage浏览器中应能看到 GraphQL 返回的 JSON。最后美化Success组件export const Success ({ weather }) { return ( section h1{weather.city}/h1 h2 img src{weather.icon} style{{ maxWidth: 2rem }} / span {weather.temp}°F and {weather.conditions} /span /h2 /section ) }进阶处理无效邮编错误校验如果用户输入了不存在的邮编如11111Service 在解析 OpenWeather 响应时找不到weather数组中的数据点前端会抛出一个难以阅读的异常。查看此时 OpenWeather 的实际响应{ cod: 404, message: city not found }因此在 Service 中检查cod字段若为404则抛出一个对用户友好的 GraphQL 错误。UserInputError由 Redwood 的 GraphQL 服务器提供见 packages/graphql-server/src/errors.ts其扩展错误码为BAD_USER_INPUTimport { fetch } from whatwg-node/fetch import { UserInputError } from redwoodjs/graphql-server export const getWeather async ({ zip }) { const response await fetch( https://api.openweathermap.org/data/2.5/weather?zip${zip},USappidYOUR_API_KEY ) const json await response.json() if (json.cod 404) { throw new UserInputError(${zip} isnt a valid US zip code, please try again) } return { zip, city: json.name, conditions: json.weather[0].main, temp: Math.round(((json.main.temp - 273.15) * 9) / 5 32), icon: https://openweathermap.org/img/wn/${json.weather[0].icon}2x.png, } }再次提交11111错误信息会以可读的形式返回。最后在 Cell 的Failure组件中把错误渲染得更像一条真正的错误提示去掉 Error: 前缀export const Failure ({ error }) ( span style{{ backgroundColor: #ffdfdf, color: #990000, padding: 0.5rem, display: inline-block, }} {error.message} /span )总结本文以「邮编查天气」为例走通了 Redwood 应用中集成第三方 API 的完整链路客户端直连简单、快速但 API Key 暴露且无法限流仅适合低风险场景服务端代理通过自建 GraphQL SDL Service 屏蔽第三方 API 的细节可以在服务端完成字段裁剪、单位转换、错误归一化API Key 安全地保存在服务端Cell 消费yarn rw g cell生成器配合QUERY/Loading/Empty/Failure/Success组件约定一站式处理数据获取与各状态渲染错误处理借助UserInputError与 Cell 的Failure组件把上游 API 的原始错误转化为对用户友好的提示。理解背后机制时可以深入阅读本仓库中以下源码packages/graphql-server/src/errors.tsUserInputError等 GraphQL 错误类定义错误码BAD_USER_INPUTpackages/graphql-server/src/directives/makeDirectives.tsrequireAuth、skipAuth等校验指令的创建与绑定机制packages/forms/src/Form.tsx 与 packages/forms/src/coercion.tsForm组件基于react-hook-form的封装、校验与空值转换策略。掌握了这套「客户端消费自家 GraphQL、服务端代理第三方 API」的模式任何 HTTP 风格的第三方服务都可以平滑接入你的 Redwood 应用。赞分享后端前端Web框架开发工具【免费下载链接】redwoodRedwoodGraphQL项目地址https://gitcode.com/gh_mirrors/re/redwood点击查看免费下载相关推荐Redwood 应用集成第三方 API 实战以 OpenWeather 天气查询为例的客户端与服务端双方案Redwood 应用集成第三方 API 实战以 OpenWeather 天气查询为例的客户端与服务端双方案 本篇技术指南以 Redwood 框架Redwoo后端前端Web框架开发工具Redwood 实战在前后端集成第三方 API以 OpenWeather 天气应用为例Redwood 实战在前后端集成第三方 API以 OpenWeather 天气应用为例 导读 在真实业务中数据往往并不都在你自己的数据库里——你可能需要后端前端Web框架开发工具Redwood 接入第三方 API 实战基于 OpenWeather 构建天气查询应用客户端与服务端双方案Redwood 接入第三方 API 实战基于 OpenWeather 构建天气查询应用客户端与服务端双方案 导读 本文基于 Redwood 官方 How后端前端Web框架开发工具创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
企业数字化 ERP 产品动态
相关推荐
Chat2DB AI SQL 客户端上手指南:接入自有模型的数据库管理工具(2026 更新) Chat2DB AI SQL 客户端上手指南:接入自有模型的数据库管理工具(2026 更新) 【免费下载链接】Chat2DB Chat2DB is a free, cross-platform, local-first database client and SQL workspace for developers, DBAs, analysts, and data teams. … · 2026/9/24 14:27:56
Flink CDC实时数据同步完整指南:3步跑通MySQL到Kafka整库同步链路 Flink CDC实时数据同步完整指南:3步跑通MySQL到Kafka整库同步链路 【免费下载链接】flink-cdc Flink CDC is a streaming data integration tool 项目地址: https://gitcode.com/GitHub_Trending/flin/flink-cdc
Flink CDC 是构建在 Apache Flink 之上的实时… · 2026/9/24 14:27:49
大麦抢票自动化完整指南:双端抢票神器如何帮你快速锁定门票 大麦抢票自动化完整指南:双端抢票神器如何帮你快速锁定门票 【免费下载链接】ticket-purchase 大麦自动抢票,支持人员、城市、日期场次、价格选择 项目地址: https://gitcode.com/GitHub_Trending/ti/ticket-purchase
还在为抢不到心仪演唱会门票… · 2026/9/24 15:33:59
RC522读卡距离总是不行?天线匹配才是硬核,从2cm到4cm的实操指南 /* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views … · 2026/9/24 15:33:41
(全新整理)顶刊复现31省份区域制度环境数据1998-2022年 文章目录资料下载地址介绍02、数据指标项目备注资料下载地址资料下载地址
点击这里下载资料
介绍
01、数据介绍
本研究参考 Shi 等人(2017)提出的省级制度脆弱性测量方式,选取樊纲市场化指数中的五项关键指标—政府与市场的关系指数、非国… · 2026/9/24 15:33:41
基于YOLOv8的渔船作业监控系统:从环境搭建到边缘部署全流程 简介:这是一套面向计算机、人工智能、自动化等专业学生与教师的毕业设计级项目资源,围绕YOLOv8实现渔船作业监控系统,可用于毕设、课程设计、大作业或项目立项演示。压缩包共97个文件,约24.21MB,以70个Python源码文件为… · 2026/9/24 0:00:13
1D-CNN时间序列建模实战:从Conv1d原理到工业落地 简介:面向时间序列数据建模的一维卷积神经网络完整实现,适合深度学习入门者及需要快速验证时序模型的研究者,能够从音频、文本、传感器或股价等序列中挖掘局部特征与时间依赖。压缩包体积很小,只有3KB,内含3个Python脚… · 2026/9/24 0:00:26
柔软的L:汉语语流中被忽视的舌肌张力控制 1. 这个“L”不是字母表里的L,而是舌尖上的L最近在几个方言群和语音教学社群里,反复看到有人发一句:“也说字母L:柔软的长舌”。初看以为是英语发音课笔记,点开才发现全是方言爱好者、播音系学生、语言康复师甚至戏曲演… · 2026/9/24 0:00:44