离子HTTP请求POST(适用于邮递员)不起作用,但GET有效

时间:2020-08-03 00:51:41

标签: laravel typescript http ionic-framework request

我正在使用localhost,在决定将其托管在000webhost上之前,我的IONIC应用程序已完成。我上传了我的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

解决方案: 由于某种原因,它可以在本地主机上运行,​​但不能在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)

}

1 个答案:

答案 0 :(得分:0)

return this.http
      .post(url, data, { headers })