I am looking to transfer information from Angular 4 to Java servlet (cross-domain)

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

Answer №1

It is important to familiarize yourself with the CORS protocol. I previously wrote an informative blog article on implementing CORS, focusing on the utilization of the Spring framework (specifically Spring Boot) rather than the Servlet API directly. The post provides a thorough explanation of how CORS operates.

Your specific issue lies in only handling POST requests. The CORS protocol entails the web browser sending an OPTIONS request to your server.

This OPTIONS request must include the Access-Control-Allow-Origin and other relevant headers in the response.

If the browser detects these headers in the response, it will proceed with the POST request.

However, if it does not find these headers in the OPTIONS response, you will encounter an HTTP error message stating something like "No 'Access-Control-Allow-Origin' header is present on the requested resource," and the POST request will not be initiated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular webpack starter - $ definition

I created a new app using the Angular 2 Starter by AngularClass. When I open the console (in both Chrome and Firebug), I can type: a = $('body') The variable a appears to be an object that looks like a DOM element. However, I am unable to run ...

What is the best way to arrange this script?

I am currently working on a Javascript script that automatically scrolls down and loads a new URL when it reaches the bottom of the page. However, I would like to add a delay of 30 seconds before the new URL is loaded. Although I am relatively new to Java ...

Tips for maintaining a marker at the bottom of the screen while zooming, similar to Google Maps

Is there a way to customize the zoom behavior in my project? I want to maintain the bottom position while resizing the other three directions, and also include pitch adjustments. https://i.sstatic.net/hQdg8.gif https://i.sstatic.net/m3xef.gif I aim for t ...

Tips for updating the value of a JSON by accessing the specific path in Java

I am trying to change the value of "$.widget.debug" in my code. I have experimented with numerous libraries, but haven't been successful in achieving this task. { "widget": { "debug": "on", "window": { "title": "Sample ...

Using conditional CSS values in Angular 8

I am currently working on a parent component and child component setup, where I am utilizing the child component's selector to display it within the parent component. Here is my child component's HTML: <div class="main-container" [n ...

Angular Fragmentary Perspective

I have a lengthy form in angular that I am currently working on. I'm wondering if there is a way to divide it into multiple views and then link each of them back to the main view. <div class="container"> <div class="row" id="part1"> ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

A special function designed to accept and return a specific type as its parameter and return value

I am attempting to develop a function that encapsulates a function with either the type GetStaticProps or GetServerSideProps, and returns a function of the same type wrapping the input function. The goal is for the wrapper to have knowledge of what it is ...

No interface 'JSX.IntrinsicElements' could be found, causing the JSX element to be implicitly of type 'any'

<Header> <title>Real Estate API Application</title> <meta name="description" content="Generated by create next app" /> <meta name="viewport" content="width=device-width, ...

Issues encountered when trying to combine ASP.NET Core with Angular 2 using the cli init feature

I am in the process of setting up a new ASP.NET Core project. In the "wwwroot" folder, I executed the command "ng init" via cmd to initialize Angular. After restoring packages, I hosted my ASP project on Kestrel. However, I encountered compile-time errors ...

Angular 2 form with ng2-bootstrap modal component reset functionality

I have implemented ng2-bs3-modal in my Angular 2 application. I am now looking for a way to clear all form fields when the close button is clicked. Can anyone suggest the best and easiest way to achieve this? html <button type="button" class="btn-u ...

Challenges of Mocking Functions in Different Files When Testing with Jest

I'm currently facing a challenge with writing tests for the CreateVendor function using Jest and Supertest. My issue lies in how to effectively mock the dependencies (generateSalt, hashPassword) in order to correctly test the behavior of the function. ...

Issue encountered during ng build using Angular 6 flag configurations

Upon attempting to build my app with specific flags, I encountered an error. When using only ng build, the process is successful. However, when adding flags such as: ng build -aot -vc -cc -dop --buildOptimize The following errors were displayed: An is ...

List of Ionic Cordova plugins sorted by Android version

Seeking guidance on how to determine which versions of Cordova plugins are compatible with Android 5.0.0. When attempting to build with the latest plugins, I encounter errors indicating that they are not supported in this version of Android. For instance: ...

XPages: create JSON data on the server, utilize on the client-side

Struggling to overcome this seemingly simple hurdle, I find myself puzzled on how to proceed. My goal is to create a JSON structure on the server using ArrayObject and ObjectObject objects, and utilize it as a datasource both on the server-side (which work ...

ReactNative: When attempting to navigate, a TypeError occurred - this.props.navigation.navigate is not a function

It's confusing to see how this issue is occurring, even though all props have been properly typed. The goal is to pass the navigator to the bottom bar component in order to navigate onPress. Initially, I define the props interface: export interface B ...

React Parent Component receiving events triggered by Child Component

How can I capture child events in the parent component? Take a look at my code to see what I am attempting to achieve. Page Component interface PageProps {} const Page: FC<PageProps> = ({}) => { //I want to avoid binding handlers here and instea ...

Exploring the Concept of Angular4 Component Nesting and Input Issues

I've taken on the challenge of completing an exercise from the book "Angular From Theory To Practice - Asim Hussain". The exercise involves refactoring an app using Angular CLI instead of having all components in the same file. You can find a sample f ...

Which is better for JSONArray parsing: Putting TRY inside LOOP or LOOP inside TRY?

I have a JSONArray that I need to parse into JSONObject. Both using a loop and try-catch are necessary for this task. My question is: Should I place the FOR loop inside the TRY block or vice versa? Does it make a difference or are they essentially the sa ...

Storing JSON data retrieved from an API into a class property using the fetch function: a step-by-step guide

I am faced with the challenge of communicating with a localhost API that I have created in my React application class. This API is responsible for returning a list of JSON data, and my goal is to store this data in a property. Having limited knowledge abo ...