The Ionic2 http post request is missing the 'Access-Control-Allow-Origin' header

Here is the complete code snippet:

this.http.post(link, data, { headers: headers })
   .map(res => res.json())
   .subscribe(data => {
       this.data.response = data._body;
    }, error => {
        console.log("Oops! An error occurred");
    });

Upon running the code, the following error message is displayed:

"XMLHttpRequest cannot load 
https://script.google.com/macros/s/AKfycbzdHHKBmLWJYZtFGlJGOrUwlPIWXor1geEOgcSgvhs/dev.     
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8100' is therefore not allowed access. 
The response had an HTTP status code of 401."

I have tried looking into CORS but it's still unclear to me...

Any assistance in resolving this issue would be highly appreciated.

Answer №1

My issue was similar, but after spending a few hours searching for a solution, it resolved itself.

ionic.config.json

{
  "name": "KickStarter",
  "app_id": "85ff0666",
  "v2": true,
  "typescript": true,
  "proxies": [
    {
      "path": "/mobile",
      "proxyUrl": "http://xxxxx:port/mobile"
    }
  ]
}

To solve the problem, use

ionic g provider [name-of-provider] --ts
. This will generate a provider to handle requests like this:

export class AuthProvider {
    data: any = null;

    constructor(public http: Http) { }

    load() {
        if (this.data) {
            // already loaded data
            return Promise.resolve(this.data);
        }

        // don't have the data yet
        return new Promise(resolve => {
            // We're using Angular Http provider to request the data,
            // then on the response it'll map the JSON data to a parsed JS object.
            // Next we process the data and resolve the promise with new data.
            this.http.get('/mobile/api/authentication')
                .map(res => res.json())
                .subscribe(data => {
                    // we've got back the raw data, now generate the core schedule data
                    // and save the data for later reference
                    resolve(this.data);
                });
        });
    }
}

Just remember: /mobile/api/authentication maps to /mobile from the path specified in the ionic.config.json.

Answer №2

Get the Allow-Control-Allow-Origin extension from the chrome web store. Activate CORS in the installed extension and run your code. This action will grant temporary CORS permission in your browser.

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

Create JSX code for rendering components outside of the main component

As someone who is diving into the world of React, I am currently on lecture 23 out of 247 on Udemy where I am learning about states and events. However, one particular question has been lingering in my mind without a definitive answer. Our company has mad ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

React - Parent Component not successfully passing Ajax data to Child Component

I have a parent component and a child component. I am using the fetch method within the componentDidMount() callback to retrieve data from an API and then set the state with key items to that data. The intention is for this data to be passed down to the ch ...

Utilizing the power of jQuery's `.clone` method to create a new window with fully

I am currently working on a project where I need to duplicate a page while maintaining its functionality, and then display it in a new window. My goal is to only clone a specific portion of the page, but for now I am focusing on replicating the entire page ...

Perform an action when a key is held down and when it is released

I am looking to implement a function that needs to be called under certain conditions: It should be triggered every second while a key is being held down (for example, if the key is held down for five seconds, it should fire 5 times every second). If ...

Utilize the HTTP path to designate the currently active tab

Here is a sample code snippet for vertical tabs in React using the Material-UI library: import * as React from 'react'; import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; import Typography from '@ ...

Refreshing the angularJS Table after adding an item does not display properly in the view

Utilizing angular and angular-material for UI design, I am able to add an item to an array but it does not update in the view. Here is my code snippet: ClientService.saveClient(client).$promise.then( function(data) { ...

A guide on manipulating an input field to trigger md-datepicker upon clicking

What is the best way to convert an input text into a fire md-datepicker and achieve a similar result like this? ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Spotlight barn doors in Three.js are an innovative feature that

I have been experimenting with three.js to build a scene featuring spotlights. Is there a way to achieve the barn door effect for the lights in three.js? I attempted using small cubes as barn doors to block the light, but it was not successful. I am look ...

What is preventing my application (docker) from connecting to the database?

Encountering a frustrating issue here: I've developed a NodeJS application with a server listening on port number 3000. The app includes simple operations such as post, put, and read, which interact with a database running in a Docker Container on por ...

Accessing the data from an HTML5 slider using JQuery

Having some difficulty fetching a value from an HTML5 slider using JQuery. Here is my code snippet: JQuery Code: // Getting the value from slider one $("#submit").on("click", function(evt) { var sliderValue = $('#slider01').attr('value ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

Is there a way to fully break out of a .forEach loop that's nested within a function?

Here is the method I am currently working with: wordFormDirty = (): boolean => { var self = this; angular.forEach(self.word.wordForms, function (wf, key) { var wordFormNgForm = 'wordFormNgForm_' + wf.wordFormId if ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

Tips for retaining component data while navigating between components in vue js

If I have two elements, the first one is named X: <template> <input required type='text' v-model.trim="number"> <input type="date" v-model="date" > <button @click='allData(number,date)'>ok</button> <t ...

How can I restrict the number of characters per line in a textarea using javascript or jQuery?

Is there a method to control the number of characters per line in a textarea? For example, on lines 1-3 of the textarea, only 20 characters can be entered, while on subsequent lines, up to 50 characters are allowed. The current structure of the textarea l ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

How can I retrieve the index of a v-for loop within a function in Vue.js HTML?

How can I splice the array from the fields in HTML Vue JS if the status is true? I also need to pass the index value to a function. Is this possible? The error I am encountering is: Uncaught ReferenceError: index is not defined at Object.success (80 ...