Java REST service remains out of reach for JavaScript fetch call

Currently, I am in the process of learning about REST API. My goal is to make a call to a POST service implemented in Java from Javascript using fetch. However, I have encountered an issue where the request fails to reach the service whenever the @Produces and @Consumes are set to MediaType.APPLICATION_JSON.

In the same API, I have successfully defined other simple POST and GET methods that work fine. It's only when dealing with sending and receiving JSON data that I face difficulties.

Here is the snippet of my fetch call:


    let options = {
        method: "POST",
        headers: new Headers({'content-type': 'application/json'}),
        body: JSON.stringify({
            "Title": "title"
        })
    };
    const url = "http://localhost:8080/myserver/data/list";
    return fetch(url, options);

Below is an excerpt of my REST API implementation:


    @Path("/data")
    public class Controller {
    
        @POST
        @Produces(MediaType.APPLICATION_JSON)
        @Consumes(MediaType.APPLICATION_JSON)
        @Path("/list")
        public Response createList(CreateListJsonData data) throws IOException {
            System.out.println("in create list");
            return Response.status(200)
                    .entity("{\"dummykey\"}:\"dummyVal\"")
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                    .build();
        }
    

The CreateListJsonData class definition looks like this:


    @XmlRootElement
    public class CreateListJsonData {
        private String Title;
        
        public String getTitle() {
            return Title;
        }
        
        public void setTitle(String title) {
            Title = title;
        }
    }

Here is also my web.xml configuration:


    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
      <display-name>myserver</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>jersey.config.server.provider.packages</param-name>
          <param-value>com.myserver</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>
    </web-app>

I am currently running the API on Tomcat within Eclipse. Upon triggering the request, the following messages appear on the console:


     com.sun.jersey.server.wadl.generators.AbstractWadlGeneratorGrammarGenerator attachTypes
     INFO: Couldn't find grammar element for class javax.ws.rs.core.Response

If anyone could offer assistance in identifying where I might be going wrong, it would be greatly appreciated.

Answer №1

This seems to be a situation involving different domains, known as CORS.

Due to the content-type used, the request is no longer considered "simple", but rather a Preflighted request. In order to handle this properly, your server must be able to process the OPTIONS method (in addition to the POST method that you are already handling). Refer to the provided link for the necessary headers that should be returned. Typically, these may include:

Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Allow-Origin: *

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

"Utilizing Node.js to access modules with their absolute

My directory structure is as follows: -- app/ |- models/ |- user.js |- config.json I am trying to make my user.js file require the config.json. Currently, I am using require('/config') but it doesn't seem to be working. Can som ...

Using HTML and C# to Deliver Emails

I've encountered a challenge with my HTML page that includes a textbox for users to input their email. When the submit button is clicked, an email should be sent to a specific email address defined in the code, and a pop-up box indicating "Email Sent" ...

What is the best way to parse a JSON file in GWT without knowing the structure

I am developing a GWT project and facing the challenge of loading and parsing JSON files with unknown schema. It seems that using overlay types may not be the best approach as I cannot predict the format of the file beforehand. Despite researching online ...

What is the best way to transfer an XML file from a server to a device using HTTP POST method?

I am in the process of setting up a server that will run on PHP, and I need to create an app for both iPhone and Android devices to parse the XML data that is sent. The app will send requests such as login and sign-in, and I am looking for guidance on ho ...

Error encountered with Passport js Local Strategy: The LocalStrategy necessitates a verify callback function

Encountering Passport JS Local Strategy Error with Node & Express I have successfully implemented OAuth 2 for Google authentication using Passport in my project. However, I am facing an error with the Local Strategy of Passport and I can't seem to fi ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Service in Angular2+ that broadcasts notifications to multiple components and aggregates results for evaluation

My objective is to develop a service that, when invoked, triggers an event and waits for subscribers to return data. Once all subscribers have responded to the event, the component that initiated the service call can proceed with their feedback. I explore ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

Issue with useState in Next.js when fetching data from an API

When attempting to retrieve data from the API, I am receiving a response. However, when trying to set the data to useState using the setAccessData function, the data is not being accessed properly. Despite trying multiple methods, the data continues to sho ...

What's the best way to serialize a NumPy array without losing its matrix dimensions integrity?

numpy.array.tostring does not retain information about the dimensions of the matrix (refer to this question), leading users to use numpy.array.reshape. Is there a method to serialize a numpy array into JSON format while keeping this information? Note: Th ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

The Fuel-ui module in Angular 2 fails to function properly when loaded from a different directory

We recently switched from ng-cli to Gulp for building our Angular2 project, and we are utilizing Fuel-ui. An unusual error has come up. We have incorporated Fuel-ui's alert component into one of our components. When referencing fuel-ui from node_mo ...

Troubleshooting an expressjs server in parallel with electron

I have managed to successfully run an ExpressJS server alongside Electron by following the instructions provided in this post: Run Node.js server file automatically after launching Electron App However, I am facing an issue where there is no output from t ...

ng-repeat not functioning properly when using track by, filter, and orderBy

I have come across this code snippet. http://jsfiddle.net/0tgL7u6e/ Scripting in JavaScript var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.nameFilter = ''; $scope.contacts = [ {name: 'G ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

The Express application appears to be unresponsive, but the data has been successfully saved to the MongoDB database. An error with the

Currently, I am delving deeper into the MERN stack and working on a straightforward CRUD application utilizing it. One of the recent additions to the app includes validators implemented through express-validator for handling requests. However, an issue ari ...

Is there a way to transform these into five columns within a single row using the Material-UI Grid system?

I'm trying to align 5 columns in one row, but I'm struggling to achieve the desired layout. Here is what I currently have: https://i.stack.imgur.com/d3z3n.png Any tips on how to make all columns appear in a single row? You can also view my att ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...