3
respostas

Erro 403 ao tentar comentar na foto

O requestInfo:

const requestInfo = {
            method : 'POST',
            body : JSON.stringify({ texto : this.comentario.value }),
            // Headers faz parte da Fetch API
            headers : new Headers({
                'Content-type' : 'application/json'
            })
        }

O endpoint:

http://localhost:8080/api/fotos/${this.props.foto.id}/comment/X-AUTH-TOKEN=${localStorage.getItem('auth-token')}

A resposta:

Response {type: "cors", url: "http://localhost:8080/api/fotos/3/comment/X-AUTH-T…Ih9Be-832MQBrJ5DxHwJzyQ-P-wp9lP49fSCmr_St-kl97nPw", redirected: false, status: 403, ok: false, …}
body:ReadableStream
bodyUsed:false
headers:Headers {}
ok:false
redirected:false
status:403
statusText:""
type:"cors"
url:"http://localhost:8080/api/fotos/3/comment/X-AUTH-TOKEN=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhbG90cyJ9.AQrl-JRJg39KeKYxMfNpnljXwxu0WOa8iYxT1Ih9Be-832MQBrJ5DxHwJzyQ-P-wp9lP49fSCmr_St-kl97nPw"
__proto__:Response

Alguma ideia?

Obrigado.

3 respostas

Rodrigo, poderia compartilhar seu código para eu dar uma olhada?

Ao final o código deveria ficar como este:

    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 => {
          Pubsub.publish('novos-comentarios',{fotoId,novoComentario});
        });      
    }

Claro, segue:

    comenta(event) {
        event.preventDefault();

        const requestInfo = {
            method : 'POST',
            // this.comentario.value utiliza acesso ao campo de formulario comentario através de ref:
            // https://reactjs.org/docs/refs-and-the-dom.html
            body : JSON.stringify({ texto : this.comentario.value }),
            // Headers faz parte da Fetch API
            headers: new Headers({
                'Content-type': 'application/json'
            })
        }

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

Aparentemente, a única diferença está nos parâmetros da função

comenta(fotoId,textoComentario)

o que não é explicação pra esse erro, de qualquer forma. Eu não conheço muito de servidores, mas pode ser que o instalura.jar tenha alguma configuração que está dando conflito? Pode ver que a resposta do servidor inclui

type:'cors'

que é relacionado à cross-domain, né?

Obrigado.

De fato, estou tendo algum problema com o instalura.jar, estou na Aula 5, a da busca, e quando vou fazer a busca, retorna o erro:

fotos:
error:"Forbidden"
message:"Access Denied"
path:"/public/fotos/alots"
status:403
timestamp:1508860231376
__proto__:Object
__proto__:Object

Vou ter que pausar esse curso até que esse problema seja resolvido. Podem me ajudar? :)

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