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

o login não esta funcionando

Ola boa noite. Ao efetuar o login me aparece:

Falha ao buscar

O meu código login:

import React, { Component } from 'react';
import {browserHistory} from  'react-router';

export default class Login extends Component {

    constructor(props){
        super(props);        
        this.state = {msg:this.props.location.query.msg};
    }

    envia(event){
        event.preventDefault();

        const requestInfo = {
            method:'POST',
            body:JSON.stringify({login:this.login.value,senha:this.senha.value}),
            headers:new Headers({
                'Content-type' : 'application/json' 
            })
        };

        fetch('http://localhost:8080/api/public/login',requestInfo)
            .then(response => {
                if(response.ok) {
                    return response.text();
                } else {
                    throw new Error('não foi possível fazer o login');
                }
            })
            .then(token => {
                localStorage.setItem('auth-token',token);
                document.cookie = `auth-token=${token}`;
                browserHistory.push('/timeline');

            })
            .catch(error => {
                this.setState({msg:error.message});
            });
    }

    render(){
        return (
            <div className="login-box">
                <h1 className="header-logo">Instalura</h1>
                <span>{this.state.msg}</span>
                <form onSubmit={this.envia.bind(this)}>
                    <input type="text" ref={(input) => this.login = input}/>
                    <input type="password" ref={(input) => this.senha = input}/>
                    <input type="submit" value="login"/>
                </form>
            </div>
        );
    }
}

O código do TimelineApi

import {listagem,comentario,like,notifica} from '../actions/actionCreator';
import 'isomorphic-fetch';

export default class TimelineApi {
    static lista(urlPerfil){
      return dispatch => {
        return fetch(urlPerfil)
        .then(response => response.json())
        .then(fotos => {    
            dispatch(listagem(fotos));
            return fotos;
        });
      }              
    }

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

        fetch(`https://instalura-api.herokuapp.com/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 => {
              dispatch(comentario(fotoId,novoComentario));            
              return novoComentario;
          }); 
      }     
    }    

    static like(fotoId){
      return dispatch => {
        fetch(`https://instalura-api.herokuapp.com/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 => {          
            dispatch(like(fotoId,liker));   
            return liker;         
          });             
      } 
    }

    static pesquisa(login){
      return dispatch => {
        fetch(`https://instalura-api.herokuapp.com/api/public/fotos/${login}`)
          .then(response => response.json())
          .then(fotos => {
            if(fotos.length === 0){
              dispatch(notifica('usuario não encontrado'));
            } else {
              dispatch(notifica('usuario encontrado'));
            }

            dispatch(listagem(fotos));
            return fotos;
          });      
      }
    }

}
6 respostas

E para Completar o código do index-view.js


import ReduxRouterEngine from "electrode-redux-router-engine";
import {routes} from "../../client/routes";
import {createStore,applyMiddleware} from "redux";
import rootReducer from "../../client/reducers";
import thunkMiddleware from 'redux-thunk';
import TimelineApi from '../../client/logicas/TimelineApi';

//const Promise = require("bluebird");

function createReduxStore(req, match) { // eslint-disable-line
  const estadoInicial = {
    timeline : [],
    notificacao : ''
  }  


  console.log(req.state);

  const store = createStore(rootReducer,estadoInicial,applyMiddleware(thunkMiddleware));
    const promise = store.dispatch(TimelineApi.lista(`https://instalura-api.herokuapp.com/api/fotos?X-AUTH-TOKEN=${req.state['auth-token']}`));

    return promise.then(() => store);

    //return null;
}

//
// This function is exported as the content for the webapp plugin.
//
// See config/default.json under plugins.webapp on specifying the content.
//
// When the Web server hits the routes handler installed by the webapp plugin, it
// will call this function to retrieve the content for SSR if it's enabled.
//
//

module.exports = (req) => {
  const app = req.server && req.server.app || req.app;
  if (!app.routesEngine) {
    app.routesEngine = new ReduxRouterEngine({routes, createReduxStore});
  }

  return app.routesEngine.render(req);
};

E por ultimo a mensagem de erro:

webpack bundle is now INVALID                                   webpack bundle is now VALID
webpack report is served from http://localhost:2992/reporter
[nodemon] restarting due to changes...
[nodemon] starting `babel-node src\server\index.js`
farmhash module not available, turning off hashKey
Just FYI: APP_SRC_DIR set to src/
Just FYI: optimizeModulesForProduction - skipping since NODE_ENV !== "production"
 > isomorphic-loader extend require: config is now VALID - webpack dev server mode <
Warning: Accessing PropTypes via the main React package is deprecated, and will be removed in  React v16.0. Use the latest available v15.* prop-types package from npm instead. For info on usage, compatibility, migration and more, see https://fb.me/prop-types-docs

Hapi.js server running at http://DESKTOP-7V60G8U:3000

{}
{}
Electrode ReduxRouterEngine Error: TypeError: Expected Array or iterable object of values: [object Object]
    at indexedSeqFromValue (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:565:13)
    at IndexedSeq (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:303:30)
    at IndexedIterable (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:34:41)
    at new List (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:2058:18)
    at timeline (C:/Users/Caio/Documents/curso/projeto-instalura-curso-aula1/projeto-instalura-ssr-codigo-ponto-partida/src/client/reducers/timeline.js:16:12)
    at combination (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:451:29)
    at dispatch (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:211:22)
    at C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux-thunk\lib\index.js:14:16
    at dispatch (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:617:28)
    at C:/Users/Caio/Documents/curso/projeto-instalura-curso-aula1/projeto-instalura-ssr-codigo-ponto-partida/src/client/logicas/TimelineApi.js:10:13
    at process._tickCallback (internal/process/next_tick.js:68:7)
Electrode ReduxRouterEngine Error: TypeError: Expected Array or iterable object of values: [object Object]
    at indexedSeqFromValue (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:565:13)
    at IndexedSeq (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:303:30)
    at IndexedIterable (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:34:41)
    at new List (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\immutable\dist\immutable.js:2058:18)
    at timeline (C:/Users/Caio/Documents/curso/projeto-instalura-curso-aula1/projeto-instalura-ssr-codigo-ponto-partida/src/client/reducers/timeline.js:16:12)
    at combination (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:451:29)
    at dispatch (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:211:22)
    at C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux-thunk\lib\index.js:14:16
    at dispatch (C:\Users\Caio\Documents\curso\projeto-instalura-curso-aula1\projeto-instalura-ssr-codigo-ponto-partida\node_modules\redux\lib\redux.js:617:28)
    at C:/Users/Caio/Documents/curso/projeto-instalura-curso-aula1/projeto-instalura-ssr-codigo-ponto-partida/src/client/logicas/TimelineApi.js:10:13
    at process._tickCallback (internal/process/next_tick.js:68:7)

E agradeço a atenção.

solução!

Fala aí Caio, tudo bem? O problema parece ser porque você está passando um Object onde deveria passar um Array ou um Iterable.

Olhando os logs, o problema parece estar no arquivo TimelineApi.js na linha 10.

Veja o retorno da API para essa chamada, verifique se é um objeto, veja o que você está mandando para o Redux.

Espero ter ajudado.

Bom dia, eu coloquei um console.log na linha 11 do TimelineApi

.then(fotos => { 
           > console.log(fotos);<
            dispatch(listagem(fotos));
            return fotos;
        });

E apareceu uma nova mensagem no meu log

{ timestamp: 1562948272314,
  status: 403,
  error: 'Forbidden',
  message: 'Access Denied',
  path: '/api/fotos' }

Obrigado, pela atenção

Obrigado logo em seguida eu vi o endereço, no login.js no metedo envia estava com o url

fetch('http://localhost:8080/api/public/login',requestInfo)

Sendo que deveria estar

fetch('https://instalura-api.herokuapp.com/api/public/login',requestInfo)

Depois disso o problema foi resolvido, muito obrigado

Boa Caio, fico feliz que tenha resolvido.

Sempre que precisar não deixe de criar suas dúvidas.

Abraços e 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