如何以角度发送卷曲请求

Posted

技术标签:

【中文标题】如何以角度发送卷曲请求【英文标题】:How to send a curl request in angular 【发布时间】:2021-12-01 02:27:50 【问题描述】:

我有以下使用邮递员的 curl 请求,我想创建一个具有相同功能的 Angular 的 http 请求

curl --location --request POST 'http://api.deepai.org/api/fast-style-transfer' \
--header 'api-key: myKey' \
--form 'content="https://www.dmarge.com/cdn-cgi/image/width=1200,quality=85,fit=scale-down,format=auto/https://www.dmarge.com/wp-content/uploads/2021/01/dwayne-the-rock-.jpg"' \
--form 'style="https://images.fineartamerica.com/images/artworkimages/mediumlarge/3/starry-night-print-by-vincent-van-gogh-vincent-van-gogh.jpg"'

这是我目前所拥有的,但我遇到了错误

constructor(private http: HttpClient) 

ngOnInit() 

async style()
    const url = 'http://api.deepai.org/api/fast-style-transfer';
    const headers = new HttpHeaders()
      .set('api-key', 'myKey');

    const resp = await this.http.post(url,  content: 'https://www.dmarge.com/cdn-cgi/image/width=1200,quality=85,fit=scale-down,format=auto/https://www.dmarge.com/wp-content/uploads/2021/01/dwayne-the-rock-.jpg',
    style: 'https://images.fineartamerica.com/images/artworkimages/mediumlarge/3/starry-night-print-by-vincent-van-gogh-vincent-van-gogh.jpg', 
      headers
    ).toPromise().then();

    console.log(resp);
  

错误:

XHRPOSThttp://api.deepai.org/api/fast-style-transfer [HTTP/1.1 400 Bad Request 1993ms]

GEThttp://localhost:8100/undefined [HTTP/1.1 404 Not Found 28ms]

错误错误:未捕获(承诺中):HttpErrorResponse: "headers":"normalizedNames":,"lazyUpdate":null,"status":400,"statusText":"Bad Request"," url":"http://api.deepai.org/api/fast-style-transfer","ok":false,"name":"HttpErrorResponse","message":"http://api.deepai.org/api/fast-style-transfer的Http失败响应: 400 Bad Request","error":"err":"错误处理给定的请求输入"

【问题讨论】:

this.http.post函数中,将 headers 替换为 headers: headers @thisdotutkarsh,我之前尝试过,但仍然没有成功 如果可能,您能否将请求标头添加到您的问题描述中? 【参考方案1】:

POST 请求正文应为 JSON,因此尝试构建一个 FormData 对象,如以下代码 sn-p 所示。

另外,将标头设置为接受 JSON 格式的数据。

async style() 
  const url = 'http://api.deepai.org/api/fast-style-transfer';
  const headers = new HttpHeaders()
    .set('accept', 'application/json')
    .set('api-key', 'myKey');

  let requestBody = new FormData();

  requestBody.append('content', 'https://www.dmarge.com/cdn-cgi/image/width=1200,quality=85,fit=scale-down,format=auto/https://www.dmarge.com/wp-content/uploads/2021/01/dwayne-the-rock-.jpg');
  requestBody.append('style', 'https://images.fineartamerica.com/images/artworkimages/mediumlarge/3/starry-night-print-by-vincent-van-gogh-vincent-van-gogh.jpg');

  const resp = await this.http.post(url, requestBody, 
    headers: headers
  ).toPromise().then();

  console.log(resp);

【讨论】:

以上是关于如何以角度发送卷曲请求的主要内容,如果未能解决你的问题,请参考以下文章

如何以角度4在帖子正文中发送数据

如何在 express/node js 中发送错误 http 响应?

如何将角度5的输入值发送到grails 3?

卷曲响应无法理解

如何在curl php中发送第二个请求时保留会话?

如何以角度9发送(div.width)