如何在React应用中用fetch调用NetSuite RestLet?token与Header放置位置
在React中用fetch调用NetSuite RestLet的正确姿势
核心逻辑:认证信息与请求头都放在fetch的配置对象里
fetch函数的第二个参数是配置对象,你需要在这里指定请求方法、请求头(包括认证token)。NetSuite的RestLet常用两种认证方式,下面分别给出可直接复用的代码示例:
1. Token-Based Authentication(TBA)示例
如果你的认证是NetSuite令牌认证,需把token相关信息通过OAuth签名放在Authorization头中:
import { useEffect, useState } from 'react'; import oauth from 'oauth-1.0a'; import crypto from 'crypto'; function EmployeeList() { const [employees, setEmployees] = useState([]); const [error, setError] = useState(null); useEffect(() => { const fetchEmployees = async () => { try { // 从环境变量读取敏感信息,绝对不要硬编码! const restletUrl = process.env.REACT_APP_NS_RESTLET_URL; const consumerKey = process.env.REACT_APP_NS_CONSUMER_KEY; const consumerSecret = process.env.REACT_APP_NS_CONSUMER_SECRET; const tokenId = process.env.REACT_APP_NS_TOKEN_ID; const tokenSecret = process.env.REACT_APP_NS_TOKEN_SECRET; // 生成OAuth签名(Postman会自动处理这一步,代码里需要手动实现) const oauthClient = oauth({ consumer: { key: consumerKey, secret: consumerSecret }, signature_method: 'HMAC-SHA256', hash_function(base_string, key) { return crypto.createHmac('sha256', key).update(base_string).digest('base64'); } }); const requestData = { url: restletUrl, method: 'GET' }; const oauthHeaders = oauthClient.authorize(requestData, { key: tokenId, secret: tokenSecret }); const response = await fetch(restletUrl, { method: 'GET', headers: { ...oauthHeaders, 'Accept': 'application/json', 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const data = await response.json(); setEmployees(data); } catch (err) { setError(err.message); } }; fetchEmployees(); }, []); if (error) return <div>错误: {error}</div>; if (!employees.length) return <div>加载中...</div>; return ( <ul> {employees.map(emp => ( <li key={emp.id}>{emp.name} - {emp.email}</li> ))} </ul> ); } export default EmployeeList;
2. 基本认证(NLAuth)示例
如果用的是NetSuite账号密码认证,直接把NLAuth格式的字符串放到Authorization头中:
import { useEffect, useState } from 'react'; function EmployeeList() { const [employees, setEmployees] = useState([]); const [error, setError] = useState(null); useEffect(() => { const fetchEmployees = async () => { try { const restletUrl = process.env.REACT_APP_NS_RESTLET_URL; // 环境变量中存储格式:NLAuth nlauth_account=xxx, nlauth_email=xxx, nlauth_signature=xxx, nlauth_role=xxx const nlAuthHeader = process.env.REACT_APP_NS_NLAUTH; const response = await fetch(restletUrl, { method: 'GET', headers: { 'Authorization': nlAuthHeader, 'Accept': 'application/json' } }); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } const data = await response.json(); setEmployees(data); } catch (err) { setError(err.message); } }; fetchEmployees(); }, []); // 渲染部分同上面的示例 }
关键注意事项
- 敏感信息隔离:把RestLet URL、token、账户信息都放在React环境变量中(比如
.env文件,变量名必须以REACT_APP_开头),绝对不要提交到代码仓库。 - 对齐Postman请求:如果Postman能正常请求,直接把Postman中"Headers"标签的所有键值对复制到fetch的headers对象中,就能保证请求和Postman完全一致。
- 错误处理:必须检查
response.ok字段,处理401认证失败、404资源不存在等HTTP错误。
内容的提问来源于stack exchange,提问作者Davidna
相关产品推荐
相关产品推荐

