需要一种方法来将response.body数据从express(server.js)发送到React(client.js)

时间:2020-03-06 21:11:57

标签: node.js reactjs rest express

我正在开发一个项目,在该项目中我提供了一个休息端点(POST),以便后端可以将响应正文发送回我的react应用程序。然后,我应该构造一个HTML页面并将该HTML发送回后端团队。现在,由于我的react应用程序不知道后端何时发送数据,因此我在本地运行该页面后最初会得到一个空白页面,因为还没有数据。一旦我使用邮递员通过在正文中添加一些内容并单击send测试该终结点,我的express(server.js)就能够获取数据,并且我可以console.log(data)将其发送,但是我无法将其发送回反应客户。

非常感谢您的帮助!

server.js

server.post('/test', urlencodedParser, function(request, response) {
    request.accepts('application/json');
    const reqBody = request.body;
    console.log(reqBody); // I am able to get the data here.

app.js

export class App extends Component {
    componentDidMount = () => {
        this.props.actions.getInitialData(); // The actions.js has the end point information.
         console.log(this.props.initialData); // This is where I need to read the data for me to construct an HTML page which I can't
    }

    render() {
        return (
            <React.Fragment>
                <div className={Styles.container} data-test="appComponent">
                    <header>
                        <h1>(Demo Data)</h1>
                    </header>
                    <Page /> 
                </div>
            </React.Fragment>
        );
    }
}

App.propTypes = {
    initialData: propTypes.object,
    actions: propTypes.object,
};

const mapStateToProps = state => ({
    initialData: state.initialData,
});

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(KspActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

这是Express与客户端浏览器的屏幕截图。]

表达js

I see data in the console once I send the data using postman

浏览器

[我在客户端浏览器上看不到任何数据]

actions.js

export function getInitialData() {
    return function(dispatch) {
        const url = `${INTERNAL_ROUTES.KSP_URL}`; // this is '/test' route

        return axios.post(url)
            .then(response => {
                const respData = response.data;
                console.log(respData); // Not able to console.log the data on update from the backend
            }).catch(error => {
                console.log(error);
            });
    };
}

reducer.js

case types.GET_KSP_DATA: {
            return {
                ...state,
                kspData: [...state.kspData, action.data]
            };
        }

1 个答案:

答案 0 :(得分:0)

您可以使用fetch从前端应用程序请求终结点,接收终结点并在应用程序中根据需要显示数据。

是这样的:

// actions.js (or where-ever your actions are defined)
getInitialData() {
return fetch('http://path.to/endpoint', {
  method: 'POST',
  body: {}
  headers: { 'Content-Type': 'application/json' }
}).then(response => response.json())
  .then(data => {
    return dispatch({ type: 'INITIAL_DATA', data)
  })
}

减速器:

const initialDataReducer = (initialState = {}, action) => {
  switch(action.type) {
    case 'INITIAL_DATA':
       return {
         ...state,
         ...action.data // NEVER use ... to spread return data, it gets messy and confusing. This is just an example.
       }
    }
}

假设您的reducer已连接到您的应用程序/组件,则应该能够将数据输入到该组件中。需要注意的一件事是,componentDidMount将没有数据,因为您在此调用操作,而componentDidMount仅运行一次。相反,componentDidUpdate将收到更改:

componentDidUpdate(prevProps) {
  if (this.props.initialData != prevProps.initialData) {
    console.log(this.props.initialData)
  }
}

很显然这里有些东西缺失/粗糙的边缘,但我希望你能明白。