【问题标题】:Ionic HTTP request POST (works on postman) not working but GET works离子 HTTP 请求 POST(适用于邮递员)不起作用但 GET 有效
【发布时间】:2020-11-23 02:31:29
【问题描述】:

我正在使用 localhost 并且我的 IONIC 应用程序几乎完成,直到我决定将它托管在 000webhost 上。我上传了非常基本的 Laravel API(我使用了 CORS 中间件),然后当我测试应用程序时,GET 请求有效,但 POST 和 PUT 无效。

注意事项:

  • URL 100% 正确,因为我在 GET 方法中使用它
  • 数据 100% 兼容,因为我在 Postman 上对其进行了测试,并且可以正常工作

This.http 是 http 服务:

this.http.getData().subscribe(s => {
    console.log('Get Works');
    this.data = s[0];
    this.http.postData(this.data).subscribe(inf => {
      console.log('Post works');
    }, err => {
        console.log(err)
        console.log('Post dont work');
    })
  })

http 服务

postData(data: any) {
  let headers: HttpHeaders = new HttpHeaders();
  headers.append("Access-Control-Allow-Origin", '*');
  headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
  headers.append("Access-Control-Allow-Headers", '*');
  headers.append('Content-Type', 'application/json');
  headers.append('Accept', 'application/json,text/plain');
  let requestOptions = { headers: headers }
  return this.http.post(url, data)}



 getData() {
let headers: HttpHeaders = new HttpHeaders();
headers.append("Access-Control-Allow-Origin", '*');
headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
headers.append("Access-Control-Allow-Headers", '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json,text/plain');
let requestOptions = { headers: headers }
return this.http.get(url, requestOptions)}

1

console

解决方案: 由于某种原因,它适用于 localhost 但不适用于 000webhost ... 它不接受正文/行请求,可能更改“内容类型”会使其正常工作 但是我的解决方案是使用 HttpParams 从角度:

postData(data: any) {
let headers: HttpHeaders = new HttpHeaders();
headers.append("Access-Control-Allow-Origin", '*');
headers.append("Access-Control-Allow-Methods", 'POST, GET, OPTIONS, DELETE');
headers.append("Access-Control-Allow-Headers", '*');
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json,text/plain');
const params = new HttpParams()
  .set('type', data.type)
  .set('email', data.email)
  .set('uid', data.uid)
  .set('lat', data.lat)
  .set('lng', data.lng)
  .set('city', data.city)
  .set('municipality', data.municipality)
  .set('subject', data.subject)
  .set('description', data.description)
  .set('image', data.image)
  .set('upvote', data.upvote)
let requestOptions = { headers: headers, params: params }
return this.http.post(url, null, requestOptions)

}

【问题讨论】:

标签: laravel typescript http ionic-framework request


【解决方案1】:
return this.http
      .post(url, data, { headers })

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 2019-08-25
  • 2019-08-28
  • 2020-11-08
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2023-03-22
  • 2019-05-27
  • 2019-09-22
相关资源
最近更新 更多