【问题标题】:is it possible to pass data in fetch options?是否可以在获取选项中传递数据?
【发布时间】:2018-07-08 04:23:42
【问题描述】:

我有一个 react 客户端应用程序。

我想用 express 包装它,这样当我从 API 获取数据时我不会遇到 CORS 问题。

现在我所有的fetches 都发生在客户端,带有一些端点 url。

如果我错了,请纠正我。 为了正确重写我的获取请求,我从我将在server.js 中定义的路由端点获取,对吗?

在我的server.js 中,我将通过 API 生成实际的fetch,对吧?

如果是这样,那我还有一个问题:

在我的客户端,我有一些逻辑将确定fetch's url 将如何。

我的问题: 有没有办法让我将正确的 url 作为某种数据传递到我的 fetch 请求中,这样我就可以在我的服务器端使用它来制作实际的 API正在取吗?

这是我的代码示例,如果可能,我会尝试理解:

const { current, amount, page} = this.pagination;
const { client_id, search } = this.API;

const limit = `_limit=${amount}`;
let currentPage;
let url;

if(this.isFetching) return;

if(direction == 'next'){
   this.pagination.current = current + amount;
   currentPage = page + 1
   let offset = `_offset=${this.pagination.current}`;        
} else {
if(page !== 1) {
    this.pagination.current = current - amount;
    currentPage = page - 1
    let offset = `_offset=${this.pagination.current}`;           
} 

url = `${search}${client_id}&${limit}&${offset}`;   //  Here is the final url

fetch('/api', {data: url})   //  PSUEDO use of fetch, is it possible?
    .then(response => response.json())       
         .then(data => {
             this.fetchedProperties = [...data.search_results];
             this.pagination.page = currentPage; 
             this.isFetching = false;                                  
         });
}

【问题讨论】:

    标签: javascript reactjs express cors fetch


    【解决方案1】:

    将数据从客户端传递到 HTTP 端点的常规方法是将其编码为查询字符串。

    http://example.com/fetch?url=http%3A%2F%2Fwww.example.net%2Ffoo%2Fbar%3Fquery%3Dsomething%26etc%3Detc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      相关资源
      最近更新 更多