我正在尝试使用Angular 2.0从我的离子应用发送一个POST请求到以下网址https://somedomain.com/MyTest/rest/register/post 但由于控制台中出现以下错误,POST请求失败。我已在POST响应中添加了必要的标头,但仍然无法通知请求。任何建议都将不胜感激。
控制台错误: 对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。
//这是REST Api POST资源:
@Path("/register")
public class JSONService{
@POST
@Path("/post")
@Produces("application/json")
@Consumes("application/json")
public Response createPlayerInJSON(RegisterPlayer player) {
String result="false";
int x = 0;
try {
JSONObject requestedJSON = new JSONObject(player);
String p_Name = requestedJSON.getString("name");
String p_Email = requestedJSON.getString("email");
String p_Mobile = requestedJSON.getString("mobile");
String p_Password = requestedJSON.getString("password");
String p_Company = requestedJSON.getString("company");
Class.forName("com.mysql.jdbc.Driver");
SoccerUtils dbConnection = new SoccerUtils();
Connection conn = dbConnection.getWeekendDBConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO mycoolmap.weekendsoccer_login values(default,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, p_Name);
ps.setString(2, p_Email);
ps.setString(3, p_Mobile);
ps.setString(4, p_Password);
ps.setString(5, p_Company);
x = ps.executeUpdate();
if(x==1){
result = "Successfully Registered";
}
conn.close();
return Response.ok("{\"name\":" + requestedJSON.getString("name") + ",\"email\":" + requestedJSON.getString("email") + ", \"mobile\":" + requestedJSON.getString("mobile") + ", \"password\":" + requestedJSON.getString("password") + ", \"company\":" + requestedJSON.getString("company") + "}")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.build();
}catch (Exception e){
e.printStackTrace();
return Response.ok("{ \"name\":\"\"}")
.build();
}
}
}
// Angular 2.0 POST请求 使用NgForm提交表单时,将调用以下函数 //signup.ts,订阅Post方法
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DataService } from '../../app/dataservice/data.service';
import { NgForm } from '@angular/forms/src/directives/ng_form';
@Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public dataService: DataService) {
}
goBackToLogin() {
this.navCtrl.pop();
}
onSubmit(form: NgForm) {
this.dataService.registerPlayer(form.value).subscribe();
}
}
// Dataservice.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
@Injectable()
export class DataService {
apiPath: string = 'http://somedomain.com/MyTest/rest/';
constructor(private httpClient: HttpClient) { }
registerPlayer(player) {
return this.httpClient.post(this.apiPath + 'register/post', player);
}
}