我正在使用localhost,在决定将其托管在000webhost上之前,我的IONIC应用程序已完成。我上传了我的Laravel API,这是非常基础的(我使用了CORS中间件),然后在测试应用程序时,GET请求有效,但POST和PUT无效。
注意:
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)}
解决方案: 由于某种原因,它可以在本地主机上运行,但不能在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)
}
答案 0 :(得分:0)
return this.http
.post(url, data, { headers })