Error: The request from http://localhost:8383 to AngularJS MySQL REST API is being blocked due to Access-Control-Allow-Origin policy

Greetings from a newcomer on 'stackoverflow.com'!

I'm encountering an issue with my AngularJS Application and I'm hopeful that the community here can provide some guidance.

To begin with, I've set up a new maven webapp project utilizing RESTful Web Services to fetch data from my mySQL-Database. Additionally, I've integrated a Cross-Origin Resource Sharing Filter.

For the Frontend, I've established a fresh HTML/JS Project using an AngularJS Seed Template.

Upon employing the HTTP findAll() Method, I successfully receive the data from the Database. findAll()_XML

However, when attempting to display this data on my AngularJS-Frontend, an error crops up:

XMLHttpRequest cannot load http://localhost:8080/myBackend/webresources/customer. Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (01:38:23:401 | error, javascript) at public_html/newhtml.html

While exploring various solutions advocating for adding Access-Control-Allow-Origin", "*" to the header, none seem to resolve the issue.

Below is the code snippet for reference. Any assistance would be greatly appreciated.


services.js:

'use strict';

var customerServices = angular.module('myApp.services', ['ngResource']);

customerServices.factory('Customers', function($resource) {

    return $resource('http://localhost:8080/myBackend/webresources/customer', {}, {
         findAll:{method:'GET',isArray:true}
    });

});

dbController.js:

'use strict';


angular.module('myApp', ['myApp.services'])

    //controller Example 2
        //controller Example 3
    .controller('dbController', function($scope, Customers) {
        $scope.allcustomers = Customers.findAll();
    });

newHtml.html:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html ng-app="myApp">
    <head>
        <title>Example-Applikation</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-resource.js"></script>
        <script src="js/friendsController.js"></script>
        <script src="js/services.js"></script>
        <script src="js/dbController.js"></script>

    </head>
    <body>      

        <br>
        <div ng-controller="dbController">
            DB-Test:
            <ul>
                <li ng-repeat="onecustomer in allcustomers">
                      Customer:  {{onecustomer.email}}
                </li>
            </ul>           
        </div>

    </body>
</html>

NewCrossOriginResourceSharingFilter.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.mybackend;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

/**
 *
 * @author
 */
@Provider
public class NewCrossOriginResourceSharingFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) {
        response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
        response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE");
        response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type");
    }


}

Customer.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.mybackend;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author loni
 */

// Remaining lines of code remain unchanged.

Answer №1

To adjust your angularjs configuration, simply include the following code:

 angular.module('yourapp')
 .config('$httpProvider',function($httpProvider){
        $httpProvider.defaults.headers.post['Content-Type'] =  'application/json';
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
        $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
 });
   //If you are receiving data in XML format, change 'application/json' to 'application/xml'

Ensure that your RESTful controller has @RequestMapping with produces = "application/json"

If the above steps do not solve the issue, consider adding @CrossOrigin("*") above your RequestMapping annotation example here

For more information on this topic, visit this link

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

What is the best way to selectively adjust object parameters in unit testing?

In my module, I have an object with several parameters. I want to rewire only specific parameters of this object. Here is a snippet from my 'module.js' file: var obj = { param_A: 'valueA', param_B: 'valueB', param_C: &a ...

Leveraging a function for filtering in AngularJS

I have developed an application where the content filter changes depending on which button is clicked. I have managed to figure out the straightforward filters, but now I am attempting to create a filter that displays content within a specified range. Bel ...

Exploring the issue of why the scroll event handler is not functioning properly within the useEffect hook

After creating a custom hook to retrieve the scroll state of an element, I noticed that the scrollHandler only triggers once. Here's my code: import { MutableRefObject, useEffect, useState } from "react" export const useScrollState = <TE ...

Can you explain the significance of the file:workspaces in the package dependencies?

Attempting to utilize npm 7 workspaces feature "workspaces": { "packages": [ "packages/apps/*", "packages/components", ], Upon installation, my package.json includes: "dependencies": ...

Using Next.js to pass data as an object in a getStaticProps function

Recently, I have started delving into the world of typescript and next.js. My current project involves deploying a Next.js web application on Vercel, which will be fetching data from a Heroku PostgreSQL database using Prisma. My goal is to display this dat ...

Utilize JavaScript and jQuery to extract the selected text's context from a webpage

I'm looking to extract the contextual information surrounding a selected text on a web page, specifically the 25 words before and after it. I've tried using JavaScript and jQuery with the following code snippet but unfortunately, it doesn't ...

Dispatching information to a designated Google Analytics tracking code

Within our website, we have a unique dimension that is configured on Google Analytics and utilized when sending the page view event: gtag('config', 'UA-TrackingCode', { 'custom_map': { 'dimension1': &apo ...

Performing an HTTP GET Request in Node.js or Express.js

Currently, I am working with express.js and require assistance in making an HTTP GET request to retrieve JSON data. Can anyone recommend some reliable node js/express js modules or libraries that can help me with performing get/post requests? ...

Tips on showcasing a set number of elements from an array in React

How can I modify my code to display only a specific number of items from the 'portfolioComponents' array, starting at a designated index ('startArrayHere') and incrementing or decrementing that index based on user interaction? I've ...

Get the total number of users and clans in a single MySQLI query

I am trying to retrieve two values from my database. This is the code I have currently for retrieving the values in two separate queries: $con = mysqli_connect("127.0.0.1", $user_database, $password_database, $nama_database) or die("User atau Password Da ...

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

Create a new chart using completely unique information

I am currently working on implementing the example found at http://bl.ocks.org/mbostock/1093130. The goal is to have the "update" function redraw the graph with a completely different dataset each time a button on the DOM is pressed. I have made some modif ...

The code is throwing an error because it is unable to find the property 'vibrate' of an

I am currently trying to implement the ng-cordova vibrate plugin in my ionic application, but I am facing an issue. The console log is showing an error message: Cannot read property 'vibrate' of undefined. Can someone please provide guidance on h ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

CSS / JavaScript Navigation Menu overshadowing Flash content in Firefox

On my website, I have a drop-down menu that was created using CSS and JavaScript. This menu drops down over a Flash animation. Interestingly, in Internet Explorer 6 and 7, the drop-down menus successfully appear over the Flash animation. However, in Mozill ...

Exploring the world of unit testing promises within JS data models in an Angular

We have integrated js-data and js-data-angular into our current project. The model we are using is as follows: (function () { 'use strict'; angular.module('dash.models') .factory('Diagnosis', ['DS', functio ...

Is there a way to update the parent component when changes occur in the child component?

I have been working on a book tracking application that allows users to keep track of the books they have read or plan to read. The app is built using Vue.js on the front end and Express.js on the server side. It consists of three lists or categories for o ...

Attempting to select an image with the intention of triggering a modal to appear through an ajax

Hi there, I recently started coding and I'm facing an issue that I can't seem to solve. I want to set it up so that when you click on an image, a modal opens corresponding to the img tag, and then the modal click event triggers a method. The prob ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

React: Applying the active class to mapped elements

I have a component that iterates over an array to generate 10 navigation items. I want to implement an onClick method that will add an active class to the clicked item. Are there any best practices using Hooks or the newer React patterns for achieving this ...