在获取网址中将网址作为参数传递

时间:2019-09-12 18:59:41

标签: javascript reactjs express request fetch

我的react组件发出GraphQL查询,并将我的“搜索”返回到数组中。这些搜索包括三个键:id,title和url。最终目标是最终将这些搜索刮掉,因此我可以从页面上获取一些信息以显示在页面上(仅供个人使用)。如果我尝试在我的React组件中进行抓取,则会遇到CORS问题。因此,我正在执行的操作是使用搜索URL将提取内容发送到前端服务器。然后服务器在该URL上运行请求,获取HTML,解析出所需信息,然后将其发送回组件。我在获取服务器URL时遇到麻烦。

我已经尝试了很多方法,但是我认为我需要做的是通过获取URL中的参数将搜索URL发送到服务器。但这是行不通的。

从将URL发送到服务器的组件中:

  querySearch = searches => {
    let searchResponses = [];
    //sends all query urls through the fetch
    searches.map(async search => {
      await fetch(`http://localhost:4100/scrape/${search.url}`)
        .then(res => res.json())
        //gets responses back and pushes all the results to the searchResponses array. 
        .then(res => searchResponses.push(res));
    });
    //sends the results back so they can be displayed on the page. 
    return searchResponses;
  };

服务器如何处理

    server.get("/scrape/:url", (req, res) => {
      request(req.params.url, function(error, response, html) {
        if (!error) {
          let newstr = JSON.parse(html.match(/listings: (\[.*\])/)[1]);
          res.send(newstr);
        } else {
          console.log("there has been an error");
        }
      });
    });

我目前遇到的主要错误是JSON问题。基本上没有得到预期的响应。

我认为我遇到了问题,因为它不喜欢将URL用作URL中的参数,这可以理解为什么这确实是问题,但为什么这样做不起作用。但是我不确定还有什么要做。

0 个答案:

没有答案
相关问题