Having trouble sending data from Angular 4 to a Java servlet due to access control restrictions. Need to figure out how to properly insert data into the database using the Java servlet.
Here is my code snippet:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions, ResponseOptions } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class DataService {
result: any;
private url = '//localhost:8080/my-java-web/';
constructor(private _http: Http) { }
addBookWithPromise(user: object): Promise<object> {
const headers = new Headers({ 'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods":" GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Credentials": "true"});
const options = new ResponseOptions({ headers: headers });
return this._http.post(this.url + 'loginsuccess', user,
options).toPromise()
.then(this.extractData)
.catch(this.handleErrorPromise);
}
private extractData(res: Response) {
const body = res.json();
return body.data || {};
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
private handleErrorPromise (error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
}
backend: java servlet
public class LoginSuccess extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.addHeader("Access-Control-Allow-Origin","*");
response.addHeader("Access-Control-Allow-Methods"," GET, POST, OPTIONS");
response.addHeader("Access-Control-Allow-Headers","Content-Type");
response.addHeader("Access-Control-Allow-Credentials", "true");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("Success" +username);
Thank You Very Much