Header contains problem with cross-domain access in $http

Sending a request through Angularjs $http with JSON data to my REST service requires setting headers once the response is returned. The necessary headers are added as follows,

Response.ok()
.entity(emp)
.headers.add("Access-Control-Allow-Origin", "*")
.headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();

However, when sending a post request without data, it works fine.

$http.post('localhost:8000/employer/register')  

On the other hand, when data is included in the post request, it fails.

$http({method: 'post', url:serverUrl, data:{name:'abc'}, headers:{'Content-Type':'application/json'} });

This snippet showcases my Rest service.

@Path("/register")
public class EmpService{

@Get
@Path("test")
@Produces
public String test(){
return "works";
}

@Post
@Consumes(MediaType.APPLICATION_JSON)
public Response addEmp(Emp emp){

return Response.ok()
.entity(emp)
.headers.add("Access-Control-Allow-Origin", "*")
.headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.allow("OPTIONS").build();  

The browser console displays the following errors:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/employer/register (Reason: CORS header 'Access-Control-Allow-Origin' missing).  
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/employer/register (Reason: CORS request failed). 

UPDATE: Upon investigation, I discovered that the service is not being invoked as there are no log outputs from Sys.out.println. Can anyone help identify where the issue lies?

Answer №1

Avoid placing the headers within the resource method. Why? The preflight request is an OPTIONS request, serving as the preliminary step to obtain the access control headers. Without an OPTIONS method defined, the browser will not trigger the @POST method to retrieve the access control headers. To address this, it is recommended to implement a filter instead and configure the headers there.

Answer №2

You could attempt the following suggestion: It is possible that the server's API route doesn't permit header data, which might be the root cause of the issue.

$http.post(url:serverUrl, data:{name:'abc'}  } );

Answer №3

Perhaps consider sending a header that the server approves of.

Give this a shot:

headers.add("Access-Control-Allow-Headers",
  "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, customHeader");

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

The Ionic Framework app is able to play YouTube videos in the browser, however, it is unable to do

I am having trouble playing a YouTube video in my Ionic app on an actual Android device, although it works fine in the browser. I found some code that might help on this link. Below is the code I am using in my Ionic app: <ion-view view-title="{{n ...

What is the location where nvm saves its node.js installations?

I'm having trouble locating where node.js installations are stored after downloading and installing through commands like: nvm install 5.0 Can anyone provide some insight on this? ...

Exceedingly High Outputs from the Haversine Formula

I am currently utilizing the Haversine formula in order to compute the distance between two specific points on the earth's surface. Below is the code snippet I am using: var app = angular.module('app', []); app.controller('firstCtr ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

Trigger an event within a linked component

I've been working on a connected component where I'm attempting to dispatch the clear action from. Here's a snippet of the code: import {createElement} from 'react'; import reduce from 'lodash/fp/reduce'; import {connect ...

Can a constant value be dynamically defined in Typescript?

Trying to dynamically define a constant in Typescript has proven to be more challenging than I anticipated. Here's what I attempted: define(name: string, value: any): boolean { var undef; const name = value; return name == undef; } ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

JavaScript's regular expression does not fully match until the end of the given string

In my JavaScript code, I am validating dates using a regular expression. The specific regular expression I am utilizing is as follows: /^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1 ...

Dynamic alteration of directive functions

Consider the directive below: app.directive("myDirective", function() { return { restrict: "AE", scope: { myFunction: '&' }, templateUrl: "some_ ...

What is the best way to create a form that includes both dynamic objects and dynamic arrays using a JSON schema?

I have observed how a JSON schema can be utilized to construct dynamic arrays. My goal is to develop a JSON web form using a JSON schema that allows for objects (dictionaries) to be expandable similar to arrays. For example, you can visit the demonstrati ...

Ways to set each tinymce editor as standard excluding a few selected ones

Currently, I am utilizing TinyMCE as my text editor for a specific project. Within the header of my codebase, I have specified that all <textarea> elements should be rendered with TinyMCE functionality. By default, these text areas have a height of 3 ...

A Step-By-Step Guide on Displaying Two Forms with Two Buttons in HTML

My goal is to develop a functionality on a webpage where users can create keys in a database. The user will need to select between two buttons, each button representing a different form to be displayed. The challenge I am facing is being able to utilize o ...

I am experiencing issues with icons not loading correctly after changing my module, with error messages indicating issues with cross-origin

Exploring various online tutorials to master the art of Angular programming has been quite an adventure for me. One tutorial introduced a module defined in this manner: .module('MyApp') However, any attempt to modify the name resulted in an er ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

Is there a way to incorporate the 'window' into middleware when using Express?

I am using middleware to retrieve data from a cookie with the help of vue-cookies. try { if (window.$cookies.get('region')) { res.setHeader('Set-Cookie', [ `region=${window.$cookies.get('region')};pat ...

Leveraging the power of JavaScript to retrieve data from PHP/MySQL

Considering creating an Android app using Appcelerators Titanium application and have a question. The website for the app is built with PHP/MySQL, and I'm curious if it's possible to dynamically pull data from the database using JavaScript in Tit ...

The process of uploading a file is interrupted by an AJAX Timeout

My HTML form includes a file input field that utilizes AJAX to upload the selected file, complete with a progress bar. However, I encountered an issue where the request would hang without any response. To prevent this from happening in the future, I aim t ...

Update the line material in three.js dynamically during runtime

Having a Line object with THREE.LineBasicMaterial, I attempted to update the material: material = new THREE.LineDashedMaterial({ dashSize: 5, gapSize: 5, }) line.material = material line.material.needsUpdate = true line.geometry.uvsNeedU ...

Sending JSON data along with sendFile() in Node.js and Express done right

After setting up a Node.js server with Express and routing, I am faced with the challenge of passing JSON data onto a specific page ("/users/id") while using sendFile(). While I could make an AJAX request on page load to retrieve the data separately, I am ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...