Encountering a CORS error while trying to access a local JSON file

I encountered an error while trying to access a local JSON file. The function I have written to retrieve the data from the JSON is as follows:

        $scope.getJSON = function () {
        (self.servicioObj = jsonFactory.GetJson('data.json')).then(
                function (dataResponse) {
                    $scope.datosJson = [];
                    $scope.datosJson = dataResponse.data;
                    self.servicioObj.detenerTiempo();
                }, function (error) {
            self.servicioObj.detenerTiempo();
        });
    }

This is the code for my Factory:

    function jsonFactory($http, $q) {

    var self = this;

    self.urlBase = 'http://192.168.0.17:8383/NewFrontEnd/app/pages/';
    self.jsonFactory = {};
    self.tiempoEspera = 120000;
    self.jsonFactory.GetJson = function (metodo) {
        var tiempo = $q.defer();
        var url = self.urlBase + metodo;
        var peticion = $http({
            method: 'get',
            url: url,
            headers: {'Access-Control-Allow-Origin': '*'},
            cache: false,
            timeout: tiempo.promise
        });
      return self.jsonFactory;
      }

Upon calling the getJSON function, I receive the following error message:

XMLHttpRequest cannot load http://192.168.0.17:8383/NewFrontEnd/app/pages/data.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.

I find it strange that I encounter this error when using '192.168.0.17' in the URL instead of 'localhost'. When I change the URL to 'localhost', there are no issues accessing the JSON file.

Answer №1

Why am I encountering this issue when I input 'localhost' in the urlBase instead of '192.168.0.17'?

The reason for this error is that 'localhost' and '192.168.0.17' are separate hostnames, resulting in different origins.

If you try to access content from one while using XHR to fetch data from the other, it will create a cross-origin request.

To resolve this, either stick to the same origin or adjust the server settings to include the necessary 'Access-Control-Allow-Origin' header.

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

Experimenting with the inner workings of a method by utilizing vue-test-utils alongside Jest

Is there a way to properly test the internal logic of this method? For instance: async method () { this.isLoading = true; await this.GET_OFFERS(); this.isLoading = false; this.router.push("/somewhere"); } This method toggles isLoading, ...

Incorporating TypeScript basics into the if statement post compiling

As I delve into the Angular2 Quickstart, I stumbled upon a peculiar issue within app.component.js after compiling app.component.ts using tsc (version 1.8.2): if (d = decorators[i]) I am unable to pinpoint where I may have gone wrong in configuring the qu ...

What could be causing this test to fail when testing my API endpoint?

Why am I encountering this error? Uncaught exception: Error: listen EADDRINUSE: address already in use :::3000 import supertest from "supertest" import axios from "axios" import app from ".." const request = supertest(app ...

Checking localStorage before sending a request with ngResource

Is there a way to check localStorage before ngResource sends a request? I want my resource object to first look in local storage before making a call to the server. Ideally, I'd like to save the initial response from the server in local storage so tha ...

Tips for retrieving headers from a POST response using AngularJS $http

Before moving forward, it's important to note that this scenario occurs within a CORS environment. On Server #1 (http://localhost:33233), which is my main website hosting SOAP and WebAPI services, I have added the following lines to the Global.asax i ...

Having trouble with multiple selectors not functioning in a jQuery click event. I attempted to use merge() to combine them, which worked successfully for the first two

Having trouble getting multiple selectors to work in a jquery click event. I attempted using .merge() but it only works for the first two selectors. var navLink = $("#carbonNavbar ul li a[href^='#']"); var sideIco = $("#sideIcons a[href^='# ...

Potential PHP/Javascript Concurrency Issue

As a newcomer to the world of web programming, I am still learning about Javascript, PHP, Ajax, and more. Despite my efforts to find a simple solution to a particular issue through Google searches, I have hit a roadblock. It seems like there might be a rac ...

Issue with AngularJS: The console.log statement is not showing any output

I recently created a controller for a login page. Below is the controller code I wrote: var authApp = angular.module('loginApp', []) authApp.controller('LoginCtrl', ['$scope', '$location', 'loginFactory', ...

JSON Attribute Name Escaping

Can't figure out how to escape attribute name in Lambda function { "statusCode": 200, "body": { "Customer_Code": "CCode", "c_type_/_customer_type": "Customer Type" } } Noticing the use of & ...

"Effortlessly transform a JSON string into a JSON Object with JavaScript - here's how

When I serialize my object using the ASP.net JavaScriptSerializer class and return it to the client side, how can I deserialize the string in JavaScript? ...

Data failing to reach controller through Ajax communication

I am completely new to working with AJAX and I'm facing an issue where nothing is happening when I click the "Start Event" button. Below is the AJAX code that I have written on my JSP page: <c:forEach items="${scheduledEvents}" var="event"> ...

The socket.io client in my JavaScript code is failing to receive the necessary event

Currently, I am in the process of configuring a socket.io chat feature with an expressjs backend and sveltejs frontend. I have established a custom namespace named 'chat' where a new room is generated upon a 'join' request. My appro ...

PHP code saves empty value to JSON file

MODIFIED Issue - After executing the function, a null value is written to the JSON file. Expectation - Gather information inputted into an HTML form and add it to an existing JSON file. Here are some of the resources from Stack that I've referenced ...

I often find myself yearning for the good old days of prototyping functions when initializing a new

I just created a module in nodejs called Test.js with the following code: function Test() { this.key = 'value'; } Test.prototype.foo = function () { return 'foo'; } module.exports = Test; Then, in B.js file: var Test = require(&a ...

Unable to implement str.replace function within HTML code

Within my Angular app, I'm looking to replace all instances of _ within a string. In my controller, the following code achieves the desired outcome: alert("this_is_string_".replace(/_/g, " ")); However, when attempting to implement the same code wit ...

Adding a Library to Your Project

Being a newcomer to importing libraries into personal projects, I am attempting to import the mathjs library package for the first time. (). However, I am running into the issue on my website where it says "math is undefined" when I try to use it. You c ...

Discover the power of Mapbox Geocoding

After implementing Mapbox's Geocoder Contro, I am thrilled with how well it is working. One thing that I am trying to figure out is how to display a marker at the exact location of the address that was searched for. Below you can see the code snippet ...

Guide on decrypting AES 128 in CryptoJS for both nodejs and web browsers

Utilizing a node.js server, I have successfully encrypted and decrypted a JSON in Base64 with the crypto node module using IV & Key. However, when I send an emit action with my AES 128 CTR JSON to a web client, I receive the JSON with base64 data encr ...

What is the process for cancelling a pending request using jQuery in JavaScript Selenium?

My website has a high volume of users clicking on one button. Waiting for long-pending ajax requests to get responses, sometimes over a minute, seems nonsensical. I understand how to wait for the response, but how can I cancel it? How do I cancel all pend ...

How can I set the position of a JavaScript popup to load automatically? It currently only works when the window

I designed a basic popup in jQuery, and everything appears to be functioning smoothly except for the on-load event in the infoPopupLoadResize() function. It's puzzling why it doesn't trigger when the page loads but works correctly during resizing ...