【问题标题】: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,我之前尝试过,但仍然没有成功
  • 如果可能,您能否将请求标头添加到您的问题描述中?

标签: json angular http curl


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2022-10-06
    • 2019-10-10
    • 2019-12-04
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多