我有一个Ionic2和spring boot api演示,它在浏览器上运行良好,但是当我在Android Emulator上运行并尝试测试该演示时,它仅适用于HTTP GET,而HTTP POST不调用API , 这是我的HTTP帖子:
import { Injectable } from '@angular/core';
import { RequestOptions, Headers, Http } from '@angular/http';
import { Events, AlertController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
/**
* Constructs the Authentication Service
* @param {Http} http
* @param {Events} events
*/
constructor(
private http: Http,
private events: Events,
private alertCtrl: AlertController
) {}
private createHeader(): RequestOptions {
let options = new RequestOptions();
options.headers = new Headers({
'Accept': 'application/json'
});
return options;
}
private login(): Observable<string> {
let authUrl = 'http://192.168.43.231:8084/api/user/test';
let data = {'phone':'8888888','password':'abc'}
return this.http.post(authUrl, JSON.stringify(data), this.createHeader()).map((data: any) => {
this.presentAlert(data);
return '';
});
}
presentAlert(data: any) {
let alert = this.alertCtrl.create({
title: 'Low battery',
subTitle: data,
buttons: ['Dismiss']
});
alert.present();
}
}
我在
中也有代理ionic.config.json
那样:
{
"name": "ionic app",
"app_id": "",
"type": "ionic-angular",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://192.168.43.231:8084/api"
}
],
"integrations": {
"cordova": {}
}
}
并且我有api测试:
@RequestMapping(value = "/api/user/test", method = RequestMethod.POST, produces = {
MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseBody
public ResponseEntity<String> test(@RequestBody LoginForm login) {
System.out.println("This test successful");
return new ResponseEntity<String>("Test", HttpStatus.OK);
}
如果我更改get功能,它将对我有用。
let authUrl = 'http://192.168.43.231:8084/api/user/test';
return this.http.get(authUrl).map((data: any) => {
this.presentAlert(data);
return '';
});
}
和服务
@RequestMapping(value = "/api/user/test", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
@ResponseBody
public ResponseEntity<String> test() {
System.out.println("This test successful");
return new ResponseEntity<String>("Test", HttpStatus.OK);
}
答案 0 :(得分:1)
除了将字符串作为HTTP POST的请求正文传递之外,我看不到任何代码问题。显然,Spring尝试将输入请求主体解析为单个String对象,从而找不到任何合适的控制器来处理请求。
将JSON.stringify(data)
替换为data
对象,就可以了。