Deployd - Information accessed through AngularJS CORS capabilities

I am currently working my way through "Pro AngularJS" by Adam Freeman where he guides the reader in building a sports store app using Angular and a Deployd server resource. The JSON data from the Deployd resource is meant to be integrated into the model, with NodeJS serving as the server running on port 5000 (

http://localhost:5000/sportsstore/app.html
). The Deployd resource itself operates on port 5500 (http://localhost:5500/products). Upon accessing the Deployd resource, the response contains:

[
    { "name": "Kayak", "description": "A boat for one person", "category": "Watersports", "price": 275, "id": "a1c999fc248b2959" },
    { "name": "Lifejacket", "description": "Protective and fashionable", "category": "Watersports", "price": 48.95, "id": "61303717cfad182e" },
    { "name": "Soccer Ball", "description": "FIFA-approved size and weight", "category": "Soccer", "price": 19.5, "id": "0fb5f67bdcbd992f" },
    { "name": "Corner Flags", "description": "Give your playing field a professional touch", "category": "Soccer", "price": 34.95, "id": "24385d315dd388b4" },
    { "name": "Stadium", "description": "Flat-packed 35,000-seat stadium", "category": "Soccer", "price": 79500, "id": "500fb6805905a856" },
    { "name": "Thinking Cap", "description": "Improve your brain efficiency by 75%", "category": "Chess", "price": 16, "id": "637d8a1f42e6fa1c" },
    { "name": "Unsteady Chair", "description": "Secretly give your opponent a disadvantage", "category": "Chess", "price": 29.95, "id": "73393312ec7dfab7" },
    { "name": "Human Chess Board", "description": "A fun game for the family", "category": "Chess", "price": 75, "id": "7871d02a662b0915" },
    { "name": "Bling-Bling King", "description": "Gold plated, diamon-studded King", "category": "Chess", "price": 1200, "id": "b59a3389a0e248bd" }
]

To fetch this data, I tried using $http.get:

$http.get("http://localhost:5500/products")
    .success(function (data) { ... })
    .error(function (error) { ... });

However, it resulted in an error:

XMLHttpRequest cannot load http://localhost:5500/products. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. 

My research indicates that there have been issues with Angular and CORS, requiring headers to be set up for cross-domain requests. So, I included the following configuration in my app.config:

$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With']; // although no longer necessary, added just in case

Despite adding these settings, I am still facing the same error. Deployd documentation suggests automatic CORS configuration (Cross-Origin Requests) with appropriate header information sent unless the request has invalid custom headers. I believe my request doesn't include any invalid custom headers:

Accept: application/json, text/plain, */*
Cache-Control: max-age=0
Origin: http://localhost:5000
Referer: http://localhost:5000/sportsstore/app.html
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36

My Query: What other setup could be required to enable Deployd to process the CORS request successfully? The book does not mention specific Angular header configurations or anything similar.

Answer №1

To resolve the issue, I recommend upgrading your deployd version to 0.6.10. This simple update resolved my problem and allowed me to successfully process a get request. It does not appear to be related to AngularJS code or Adam Freeman's book.

In Freeman's book, he includes the deployd program in the source code download available at http://www.example.com/book. The version included is 0.6.9, which should work just fine. If you prefer to use version 0.6.10, you can find it here:

https://www.example.com/deployd/0.6.10

Keep in mind that this is not an installer; you will need to manually replace the node_modules directory in your deployd installation with the updated files.

Answer №2

To ensure you have the latest version 0.6.10 of deployd, simply execute the command "npm update" in your installation folder. This solution worked for me after referring to javaauthority's helpful responses (much appreciated!).

Answer №3

To incorporate your files (app.html, sportStore.js, ...) into your deployd project, simply store them in the public directory and access them through the URL: http://localhost:5500/app.html

Answer №4

To resolve the problem, my solution involved launching Chrome with the "--disable-web-security" parameter. Before implementing this step, ensure to open Task Manager and terminate all existing Chrome processes.

Answer №5

After successfully addressing the CORS issue while using Wildfly (JBOSS 8.X), I felt compelled to share my solution for those not utilizing the Deployd web server mentioned in the book. In order to make it work, I went ahead and created a straightforward Java class named CorsFilter specifically tailored for Wildfly. Locating the necessary imports shouldn't be too challenging for anyone running Wildfly.

I sincerely hope that this information proves beneficial to individuals encountering similar obstacles with different web servers.

It's worth mentioning: responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");

Did you notice the "*" in the aforementioned line? This essentially permits ANY requests to go through. While this may suffice for local development purposes, it is imperative to enforce stricter security measures for Production/Staging environments. For instance, restricting requests solely from specific IP addresses.

import org.jboss.resteasy.annotations.interception.HeaderDecoratorPrecedence;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * Class to .
 * User: Java Authority
 * Date: 12/6/2014
 * Time: 12:38 PM
 */
@Provider
@ServerInterceptor
@HeaderDecoratorPrecedence
@WebFilter
public class CorsFilter implements ContainerResponseFilter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest r = (HttpServletRequest)request;
        HttpServletResponse s = (HttpServletResponse)response;
        chain.doFilter(request, response);
    }


    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    }
}

Answer №6

When working with deployd, I found a helpful solution using fiddler to tweak the responses. By following this guide, you can learn how to customize fiddler and easily add Access-Control-Allow-Origin: * header to all responses for improved functionality.

Check out this link for more information!

Answer №7

DPD is rejecting custom headers sent by Angular. To resolve this issue during development, include the following code in your project to remove these headers and allow DPD to function properly:

delete $http.defaults.headers.common['X-Requested-With'];

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

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

Issue with dynamic-rooms causing networked Aframe project to malfunction

I am currently working on a project using A-frame() along with the networked A-frame component: https://www.npmjs.com/package/networked-aframe To view the project, click here: I encountered an issue when attempting to replace the following code in scene. ...

I am curious about the significance behind 'this.object.position' within the trackball feature of Three.JS

After spending quite some time delving into the code of this Trackball control, I am puzzled by what exactly this.object.position represents. You can find the code here: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/TrackballControls. ...

I have a Three.js Group containing five elements, but I am having trouble accessing the meshes within. Is there a way to properly access the meshes within a Three.js group?

https://i.sstatic.net/cfznC.png I am encountering an issue while trying to access elements within this array. Despite there being a length of 5, the code returns "undefined" and has a length of 0. The image above shows the output of this code. console.log ...

Encountering a handshake error when connecting Node.js and MySQL modules

After working with Codeigniter for years, I found myself needing to use MySQL in Node.js. However, connecting the libraries has been a messy and tricky process, with connection issues being my main problem. I'm currently developing an adapter to hand ...

The functionality of the `next-auth` signOut button click does not seem to accept a variable as input, although

The Nav.jsx component code provided is working as intended. In this implementation, clicking the 'Sign Out' button will redirect the application to http://localhost:3000. 'use client' import { signOut } from 'next-auth/react&apos ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

I have a specific resolution in mind where I want to run jQuery code during window scrolling

I have a jQuery code that I want to run only when the resolution is greater than 950px. If not, I risk losing the responsive logo. My goal is to create a navigation bar similar to the one on the Lenovo homepage. $(document).ready(function(){ //left ...

The process of transferring a file from a client to a server and then from one server to another

Within my web application, I am currently working on implementing a file upload feature. I have successfully utilized axios to send file requests from the client to the server's API, including proper form data appending and necessary headers. However, ...

Error in Node.js: Unable to access 'text' property because it is undefined

I am currently developing a messenger bot using node.js and express. In order to organize my code better, I have decided to split my index.js file into two separate files. One of them is msg.js which contains the following code: 'const express = re ...

Retrieve information from data properties in the Froala editor

I'm currently developing a custom toolbar button for Froala Editor. To execute my desired action, I require access to a data attribute stored within the original textarea. Is there a recommended method for accomplishing this task? Appreciate your as ...

Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this: HTML: <div class="container" id="cont"> <div class="box show"></div> </div> CSS: .container { width: 100vw; height: 100vh; } .box { position: absolute ...

Flipped the dimensions of an image for better responsiveness

Trying to implement this particular design on a responsive website. Wondering if there's a way to establish an inverse resizing technique using jQuery / Javascript so that as the viewport shrinks, the text size increases. Attempted to use jQuery to a ...

How can you tell when directionsService has finished processing and returned its status?

Within the code snippet below (keep an eye on the error console!), I am rapidly querying Google Maps for ten different locations to determine whether it can calculate a route to them or not. While this method does work, I require the result from Google to ...

jQuery struggles to properly interpret JSON data retrieved from a PHP file

I have successfully encoded WordPress data as JSON for a store locator page, however, I am encountering an issue where the page fails to parse the returned JSON. Even though the file is present and it indeed returns the correct JSON data, I receive a 404 N ...

Retrieve the CSS attributes within a directive specifically designed for child elements

Currently, I am iterating through the child elements of the element to which the directive is attached, and adding mouseup and mousedown callbacks: var dragDroppables = element[0].children; for (var elementIdx = 0; elementIdx < dragDroppables. ...

Is it possible to utilize one controller within another controller in angularjs?

I am interested in using the Angular JS scrollbar to display content. Here are the controllers I plan to utilize: module.controller('itemsCtrl', function($scope){ $scope.items = [ {src:'../static/images/image-3.png&apos ...

Providing an Object as the Output of an Event Handler, in cases where the data cannot be transformed into another format

My goal is to have the second dropdown menu, labeled Item, dynamically update when a category is selected from the first dropdown menu, labeled Type. If I could access the array I created within the change event, I could easily populate the second dropdow ...

Display or conceal content depending on the height of a div element

I need help with the following code. I want to hide the second paragraph by default and show it only when the blue circle is clicked and the div is expanded. Here is the code: What this code does is calculate the inner height of a specific element and s ...

Textures in Three.js are rendered as a solid black color during loading

Snippet: let loader = new THREE.TextureLoader(); let texture = loader.load('resources/earth.png'); let geometry = new THREE.SphereGeometry( 3.7, 32, 32 ); let material = new THREE.MeshBasicMaterial( { map: texture }); let sphere = new THREE.Mes ...