【问题标题】:Redirect/ Routing issues in React and ExpressReact 和 Express 中的重定向/路由问题
【发布时间】:2019-08-23 02:45:45
【问题描述】:

我正在创建一个进行外部 api 调用的航班搜索应用程序。数据将在搜索结果组件中重新组织并返回。

在提交时,数据被发送到 express,大约需要 10 秒或更长时间才能完成所有 api 调用。

我认为我在 api 调用延迟期间的某个时候需要一个加载器,但我也不确定如何发送/呈现数据。

就目前而言,我有两个页面 home.js- '/' 我在其中进行搜索并发送到服务器端,而 price.js- '/search' 在加载时从 json 文件中获取数据.但我没有连接它们

这两个文件都可以,但我需要连接它们。当我按下提交时,用户输入被发送到服务器并进行 api 调用,但为了看到结果我必须手动刷新 localhost:3000/search。

在所有 api 调用之后的 express 应用程序中,我尝试了 res.redirect 方法,但是给出的错误是在发送到客户端后设置标头。

作为反应,我在提交后尝试重定向到搜索页面。但是我无法让它重定向,并且一旦调用 /search 页面,它就会从文件中获取数据。这将在 api 完成写入文件之前发生,因此将呈现以前的搜索结果。

--in app.js 
setTimeout(() => {
        Promise.all([promise, promise2]).then(values => {

            return res.redirect('http://localhost:3000/search');

        });
    }, 25000);

I had to wrap the api calls in promises so it will only redirect after all is written to file. 

(在反应价格.js)

 componentDidMount() {

   fetch('/search')
            .then(res => {

                return res.json()

            })
            .then(res => {

                console.log(res.toString());


                this.setState({flightData: res});

            })
            .catch(error => console.log(error));
    }

home.js

home.js

```
onChange = (e) => {
    this.setState({
       originOne: e.target.value, originTwo: e.target.value});
    };


 onSubmit = (e) => {
     e.preventDefault();

     const { originOne, originTwo ,redirectToResult} = this.state;


};


```
app.js - I have all the functions calling each other in a waterfall style ( probably not the best way I know) 

app.post('/', function getOrigins(req,res) {

     var OrigOne;
     var OrigTwo;

....

function IataCodeSearchOrg1(res, OrigOne, OrigTwo) {
... 
findPrices(res,A,B)
}

 function findPrices(res, A, B) {

         promise = new Promise(function (resolve) {
...
}
}

All the methods are called within eachother. The api calls are in a loop and after each iteration they are written to the json file. 

All these functions are in the app.post method and i tried to res.redirect but it did not work.  

【问题讨论】:

  • 你能分享剩下的相关服务器代码吗? app.js 中的部分似乎不完整

标签: javascript reactjs api express search


【解决方案1】:

编辑:

您不能从 XHR 请求重定向服务器端。您需要重定向客户端。

例如

componentDidMount() {

   fetch('/search')
       .then(res => res.json())
       ...
       .then(() => window.location = '/myredirecturl')
} 

【讨论】:

  • 感谢您的回复,我已经在价格页面上渲染了数据,但是一旦快速完成api调用,我就无法重定向到价格页面。虽然我可能没有以正确的方式这样做,但我应该重定向到价格页面服务器端还是客户端?
猜你喜欢
  • 2020-11-11
  • 2013-03-26
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2020-08-26
相关资源
最近更新 更多