NextJS中Fetch调用NestJS API无法获取业务数据问题求助
问题描述
在NextJS中使用Fetch调用NestJS开发的API时出现异常:通过Postman调用该API能正常返回包含id和status的响应,但使用Fetch调用仅得到状态码201的Response对象,无法获取具体业务数据。需要将返回的tracking id传递到UI中。
预期行为:获取与Postman调用一致的响应内容。
后端 - NestJS的API服务与控制器代码
事务处理服务代码
async createTxnVaultToVault(txn: Txn) { this.logger.log("Creating transaction for account: " + txn); this.logger.log("Transaction data: " + JSON.stringify(txn)); const payload: TransactionArguments = { assetId: txn.asset, source: { type: PeerType.VAULT_ACCOUNT, id: String(txn.source) }, destination: { type: PeerType.VAULT_ACCOUNT, id: String(txn.dest) }, amount: String(txn.amount), fee: String(txn.fee), note: txn.note }; this.logger.log("TXN Payload data: " + JSON.stringify(payload)); return fireblocks().createTransaction(payload) .then(res => res) .then(res => { console.log(res) return res; }) .catch(err => { console.log(err); return err; }); }
控制器代码
@ApiTags('Fireblocks Transactions - Create Vault to Vault Transaction') @Post('/createTxnVaultToVault') async createTxnVaultToVault( @Body() txn: Txn ): Promise<any> { return this.appService.createTxnVaultToVault(txn) .catch(e => { this.logger.log(e); return getError(e); }); }
前端 - NextJS的Fetch代码
export async function transferFunds(txn) { const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault"; console.log(txn); return fetch(req_url, { method: 'POST', headers: { Accept: "application/json", "Content-Type": "application/json", 'Access-Control-Allow-Origin': '*' }, body: JSON.stringify(txn) }) .then(resp => { console.log(resp); }) .then(resp => { console.log(resp); return resp; }) .catch(err => { console.log(err); }); }
解决方案
核心问题
Fetch API返回的Response对象仅包含响应元数据(如状态码、响应头),不会自动解析响应体。当前代码未调用解析方法,导致无法获取业务数据;同时前端请求头中的Access-Control-Allow-Origin属于冗余配置,该字段应由后端在响应中设置。
修改后的前端代码
export async function transferFunds(txn) { const req_url = process.env.NEXT_PUBLIC_FIREBLOCKS_SERVER + "/createTxnVaultToVault"; console.log(txn); return fetch(req_url, { method: 'POST', headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(txn) }) .then(resp => { // 校验响应状态,非成功状态抛出错误 if (!resp.ok) { throw new Error(`请求失败,状态码:${resp.status}`); } // 解析响应体为JSON格式 return resp.json(); }) .then(data => { console.log(data); // 此处可获取包含id和status的业务数据 return data; // 将数据返回给UI层使用 }) .catch(err => { console.error(err); throw err; // 抛出错误便于上层处理 }); }
后端CORS配置(若存在跨域问题)
如果前后端存在跨域,需在NestJS的main.ts中启用CORS:
async function bootstrap() { const app = await NestFactory.create(AppModule); // 生产环境可配置具体来源、方法等参数,示例为允许所有来源 app.enableCors(); await app.listen(3000); } bootstrap();
内容的提问来源于stack exchange,提问作者Mabel Oza
相关产品推荐
相关产品推荐

