Function fecth: The CORS header 'Access-Control-Allow-Origin' is not present

Asked

Viewed 210 times

0

I am trying to simulate an application I am running on a local Glassfish server. The IDE I am using is: Intellij. I built a method that consumes an API service from an address:

http://localhost:8080/<BACKEND>/rest/home/listar

I’m trying to consume through the address:

http://localhost:3002/

This is the error generated in the browser:

Blocked cross-origin request: Same origin policy (Same Origin Policy) prevents reading the remote resource on http://localhost:8080//Rest/home/listar. (Reason: CORS header 'Access-Control-Allow-Origin' is not present). Networkerror when attempting to fetch Resource.

The algorithm I used in my frontend application was:

Homecontroller.ts

importaLista() {

        function isOk(res : any) {
            if (res.ok) return res;
            else throw new Error(res.statusText);
        }

        fetch('http://localhost:8080/corujito.com-1.0-SNAPSHOT/rest/home/listar')
            .then(res => isOk(res))
            .then(res => res.json())
            .then(
                (dados:any[]) => {
                    dados.map(dado => new Ensaio(dado))
                    .forEach(ensaio => this._ensaios.adiciona(ensaio))

                }
            ).catch(
                err => console.log(err.message)
            );
    }

Ensaiodao.ts

import { Ensaio } from "../models/Ensaio";

export class EnsaioDao {

    private _listas: Ensaio[] = [];

    adiciona(negociacao: Ensaio): void {
        this._listas.push(negociacao);
    }

    paraArray(): Ensaio[] {
        return ([] as Ensaio[]).concat(this._listas);
    }

    paraTexto(): void {
        console.log('Impressão');
        console.log(JSON.stringify(this._listas));
    }

}

app ts.

import { HomeController } from "./controllers/HomeController";

const homeController = new HomeController();

homeController.importaLista();
console.log(homeController.getList());
  • @wmsouza It is not a duplicate publication. Despite using AJAX, the mode I am using is by the fetch() function. The code above demonstrates. But I appreciate your support.

  • 1

    localhost:8080 is different from localhost:8080, so there is no way to solve it on the front end, this has been much debated on the site, Cors resolves itself in the back end and your back end is the "Glassfish server", so you have to solve it in your we-request on http://localhost:8080//rest/home/listar

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.