React调用Node.js代理API接口请求一直pending无法获取返回数据问题
核心故障原因
- Node代理层未向前端返回响应:你在
request的回调逻辑中仅打印了日志、返回了内部response变量,完全没有调用Express的res对象向前端发送响应数据,导致前端的HTTP请求一直处于等待响应的pending状态。 - 错误变量引用:报错分支中使用了未定义的
err变量,你接收的错误参数名实际为error,代码运行到报错分支会直接抛出未定义错误。 - Axios响应属性取值错误:Axios返回的响应对象中状态码字段为
status而非statusCode,你写的判断条件永远无法命中。 - 响应数据取值错误:Axios返回的业务数据默认存放在
data字段而非body字段,且Node层需要主动把第三方API返回的结果发送给前端才能正常取值。 - setState回调逻辑错误:你当前写的
console.log是同步执行的,不会等setState更新完成后运行,打印的永远是更新前的旧状态值。
修正后Node.js代码
const express = require('express'); const request = require('request'); const app = express(); app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', '*'); next(); }); app.get('/ListAllModels', (req, res) => { request( { url: '/* api url*/', headers: { 'Content-Type': 'application/xml', 'X-Tenant-ID': '/*tenant id*/', 'Authorization': 'Basic /*authorization*/' } }, (error, response, body) => { if (error || response.statusCode !== 200) { return res.status(500).json({ type: 'error', message: error.message }); } console.log(response); // 核心修正:调用res方法把结果返回给前端 return res.json(body); } ) }); const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`listening on ${PORT}`));
修正后CallService.js代码
import axios from 'axios'; export const getAllEmailModels = () => { return axios.get("http://localhost:4000/ListAllModels").then(response => { // 修正状态码字段为status if (response.status === 200) { return response.data; } throw new Error("Network response was not ok."); }).catch(error => { throw error; }); };
修正后React组件代码
import React, { Component } from 'react' import * as CallService from "../Services/CallService"; export default class Login extends Component { constructor(props) { super(props); this.state = {emailModels:[]}; this.emailModelTest = this.emailModelTest.bind(this); } emailModelTest() { console.log("button works"); CallService.getAllEmailModels().then(data => { this.setState({ emailModels: data, // 把log放到setState回调中,拿到更新后的状态 }, () => console.log(this.state.emailModels)); }).catch(err => { console.error('请求出错:', err); }) } render() { return ( <div> <button onClick={this.emailModelTest}>test call</button> </div> ) } }
内容的提问来源于stack exchange,提问作者imkeVr
相关产品推荐
相关产品推荐

