如何将后端作为外部网址和前端之间的桥梁,用于检索文件?

huangapple go评论75阅读模式
英文:

How to make backend as a bridge between external url and frontend for retrieving files?

问题

I am trying to get a .pbf file from a map server. (but the question expands to pdf, jpg or csv)
我正在尝试从地图服务器获取.pbf文件。(但问题扩展到pdf、jpg或csv)

I wanna obtain that .pbf file and return it in a GET request.
我想获取那个.pbf文件并在GET请求中返回它。

The file comes from a private server: http:XXX.XXX.XXX.XXX/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf
该文件来自私有服务器:http:XXX.XXX.XXX.XXX/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf

And want to return the exact same file to a get API in mi backend, like:
并希望将完全相同的文件返回给后端的GET API,例如:

http://localhost:3001/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf

So to use my backend as a bridge between mi react app, and the geometrictiles server.
因此,将我的后端用作我的React应用程序和geometrictiles服务器之间的桥梁。

I generated and endpoint in my controller like:
我在我的控制器中生成了一个端点,如下:

async getGeoTiles(){
  const data = await this.geomService.getPBF('layername',11,585,783);
  // const file = createReadStream(join(stringdata, 'package.json'));
  // return 
  // new StreamableFile(file);
  return stringdata;
}```

And in my service:
在我的服务中:

```async getPBF (layername, z, x, y){
// just using a json route in order to test any file
    return this.httpService
    //here should be this URL, but for testing reasons
    //http:XXX.XXX.XXX.XXX/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf
    .get('https://api.coindesk.com/v1/bpi/currentprice.json')
    .pipe(
      map((res) => {
        // console.log('res', res);
        return res.data;
      })
    )
    .pipe(
      catchError(() => {
        throw new ForbiddenException('API not available');
      }),
    );
  }```

But this is not returning the file json, csv nor PBF as I need.
但这不返回我需要的json、csv或PBF文件。

How is this is done?
这应该如何完成?

<details>
<summary>英文:</summary>

I am trying to get a .pbf file from a map server. (but the question expands to pdf, jpg or csv) 
I wanna obtain that .pbf file and return it in a GET request. 


The file comes from a private server: `http:XXX.XXX.XXX.XXX/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf`

And want to return the exact same file to a get API in mi backend, like:
`http://localhost:3001/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf`

So to use my backend as a bridge between mi react app, and the geometrictiles server. 


I generated and endpoint in my controller like: 

@Get(&#39;/geoserver&#39;)
async getGeoTiles(){
const data = await this.geomService.getPBF(&#39;layername&#39;,11,585,783);
// const file = createReadStream(join(stringdata, &#39;package.json&#39;));
// return
// new StreamableFile(file);
return stringdata;
}

And in my service:
async getPBF (layername, z, x, y){
// just using a json route in order to test any file
return this.httpService
//here should be this URL, but for testing reasons
//http:XXX.XXX.XXX.XXX/geometrictiles/${source.layername}/{z}/{x}/{y}.pbf
.get(&#39;https://api.coindesk.com/v1/bpi/currentprice.json&#39;)
.pipe(
map((res) =&gt; {
// console.log(&#39;res&#39;, res);
return res.data;
})
)
.pipe(
catchError(() =&gt; {
throw new ForbiddenException(&#39;API not available&#39;);
}),
);
}

But this is not returning the file json, csv nor PBF as I need. 

How is this is done? 

</details>


# 答案1
**得分**: 0

To get file using HttpService you should inject response in getGeoTiles method and write result of HttpService GET method to it response. Also, you should write 'Content-Disposition' header to response object.

Here's example of this logic to retrieve file from a specific URL:

```typescript
@Controller()
export class AppController {
  constructor(private readonly httpSerivce: HttpService) {}

  @Get('/geoserver')
  async getGeoTiles(@Res() response: Response) {
    const { data } = await firstValueFrom(
      this.httpSerivce
        .get<ArrayBuffer>('https://api.coindesk.com/v1/bpi/currentprice.json', {
          // get the content as ArrayBuffer
          responseType: 'arraybuffer',
        })
        .pipe(
          catchError(() => {
            throw new ForbiddenException('API not available');
          }),
        ),
    );
    response.setHeader(
      'Content-Disposition',
      // Here write filename instead of 'currentprice.json'
      `attachment; filename=${encodeURI('currentprice.json')}`,
    );
    // write content to response object
    response.write(data);
    // finalize
    response.end();
  }
}
英文:

To get file using HttpService you should inject response in getGeoTiles method and write result of HttpService GET method to it response. Also, you should write 'Content-Disposition' header to response object.
<br>
Here's example of this logic to retreive file from specific url:

@Controller()
export class AppController {
  constructor(private readonly httpSerivce: HttpService) {}

  @Get(&#39;/geoserver&#39;)
  async getGeoTiles(@Res() response: Response) {
    const { data } = await firstValueFrom(
      this.httpSerivce
        .get&lt;ArrayBuffer&gt;(&#39;https://api.coindesk.com/v1/bpi/currentprice.json&#39;, {
          // get the content as ArrayBuffer
          responseType: &#39;arraybuffer&#39;,
        })
        .pipe(
          catchError(() =&gt; {
            throw new ForbiddenException(&#39;API not available&#39;);
          }),
        ),
    );
    response.setHeader(
      &#39;Content-Disposition&#39;,
      // Here write filename instead of &#39;currentprice.json&#39;
      `attachment; filename=${encodeURI(&#39;currentprice.json&#39;)}`,
    );
    // write content to response object
    response.write(data);
    // finalize
    response.end();
  }
}

huangapple
  • 本文由 发表于 2023年4月7日 04:37:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定