Solucionado (ver solução)
Solucionado
(ver solução)
4
respostas

Cross-Origin Request Blocked

Ao alterar os métodos like() e comenta() de FotoAtualizacao, para chamar os métodos da TimelineStore (através do this.props.like e this.props.comenta), passados por parâmetro pelo Timeline, lança esse warning de CORS e o erro "TypeError: NetworkError when attempting to fetch resource.".

Código novo:

like(event){
        event.preventDefault();
        this.props.like(this.props.foto.id);
    }

    comenta(event){
        event.preventDefault();
        this.props.comenta(this.props.foto.id, this.comentario.value);
    }

Se eu utilizar da forma antiga, funciona normalmente, tanto o like() quando o comenta():

like(event){
        event.preventDefault();

        const url = `https://instalura-api.herokuapp.com/api/fotos/${this.props.foto.id}/like?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`;

        fetch(url, {method: 'POST'})
        .then(response => {
            if(response.ok)
                return response.json();
            else{
                // console.log('response: ', response);
                throw new Error("Não foi possível realizar o like da foto");
            }
        })
        .then(liker =>{
            // console.log('liker: ', liker);
            this.setState({ liked : !this.state.liked });
            Pubsub.publish('atualiza-liker', {fotoId:this.props.foto.id, liker: liker});
            // Pubsub.publish('atualiza-liker', {fotoId:this.props.id, liker}); shortest hand
        });
    }

Os métodos dentro do TimelineStore estão assim?

    comenta(fotoId,textoComentario) {
      const requestInfo = {
        method:'POST',
        body:JSON.stringify({texto:textoComentario}),
        headers: new Headers({
          'Content-type':'application/json'
        })
      };

      fetch(`http://localhost:8080/api/fotos/${fotoId}/comment?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`,requestInfo)
        .then(response => {
          if(response.ok){
            return response.json();
          } else {
            throw new Error("não foi possível comentar");
          }
        })
        .then(novoComentario => {
            const fotoAchada = this.fotos.find(foto => foto.id === fotoId);        
            fotoAchada.comentarios.push(novoComentario);
            Pubsub.publish('timeline',this.fotos);
        });      
    }    

    like(fotoId){
      fetch(`http://localhost:8080/api/fotos/${fotoId}/like?X-AUTH-TOKEN=${localStorage.getItem('auth-token')}`,{method:'POST'})
        .then(response => {
          if(response.ok) {
            return response.json();
          } else {            
            throw new Error("não foi possível realizar o like da foto");
          }
        })
        .then(liker => {          
            const fotoAchada = this.fotos.find(foto => foto.id === fotoId);
            fotoAchada.likeada = !fotoAchada.likeada;

            const possivelLiker = fotoAchada.likers.find(likerAtual => likerAtual.login === liker.login);

            if(possivelLiker === undefined){
                fotoAchada.likers.push(liker);
            } else {
                const novosLikers = fotoAchada.likers.filter(likerAtual => likerAtual.login !== liker.login);
                fotoAchada.likers = novosLikers;
            }
            Pubsub.publish('timeline',this.fotos);
        });              
    }
4 respostas

Phillipe, bom dia!

Você poderia compartilhar seu código via github? Assim podemos fazer alguns testes, me parece que o seu código ficou um pouco diferente que a do instrutor. por exemplo o uso do this.fotos dentro do TimelineStore

Aguardo sua resposta e bons estudos!

segue link do projeto no github: https://github.com/PhilippeBrissant/instalura

solução!

Descobri o erro!

Na Store eu estava tentando acessar a API local (localhost) em vez de acessar a API externa do herokuapp.

Falha no engano. Me desculpem! :)

Oi Philippe tudo certo ?

Que bom que resolveu, não deixe de marcar sua resposta como solução, assim, caso outros alunos tenham o mesmo problema vão encontrar mais fácil.

Bons Estudos !

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software