0

I am having trouble connecting my node.js back-end code that is connected and working fine when they run on back-end, but when I try to use these functions in the front-end react.js it doesn't work. I am receiving an error of unexpected token, I think because it is fetching the wrong data.

Here's my back-end desktop\test\src\users.js:

var express  = require('express');

var app   = express();                             

var Firebase = require('firebase');

var morgan = require('morgan');      

var bodyParser = require('body-parser');    

var Rebase = require('re-base');

app.use(function(req, res, next) { 

res.setHeader("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");

res.header("Access-Control-Max-Age", "3600");

res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

next();

});


Firebase.initializeApp({

apiKey: test.apiKey,

authDomain: test.authDomain,

databaseURL: test.databaseURL,

projectId: test.projectId,

storageBucket: test.storageBucket,

messagingSenderId: test.messagingSenderId,

serviceAccount: './testapp.json', 

});


var db = Firebase.database();

var usersRef = db.ref("Users/");
console.log("reached here.");
 app.get('/api/users', function(req, res) 
 {
     var array = [];
     usersRef.on("value", function(snapshot)
     {
         snapshot.forEach(function(data) 
         {
             var usernames =data.child("username").val();
             var user = { "username": usernames};
             array.push(user);
         });
          res.json(array);
      });
     });
     app.listen(8000);

 console.log("port is 8000");

desktop\test\src\test.js contains my firebase information. I've put X's just for the sake of showing it here.

module.exports = {     
apiKey: "XXXXXXXXXXXXXXXXXXXXXXUrQT8_WyGeZYSkNIA",
authDomain: "authentication-efba4.firebaseapp.com",
databaseURL: "https://authentication-efba4.firebaseio.com",
projectId: "authentication-efba4",
storageBucket: "authentication-efba4.appspot.com",
messagingSenderId: "XXXXX8179075"

 };

Here's my front-end desktop\test\src\App.js:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {users: []}

  componentDidMount() {
    fetch('/users')
      .then(res => res.json())
      .then(users => this.setState({ users }));
  }

  render() {
    return (
      <div className="App">
        <h1>Users</h1>
        {this.state.users.map(user =>
          <div key={user.id}>{user.username}</div>
        )}
     </div>
    );
  }
}

export default App;

It is not fetching the data from the database, I cannot even compile it when I run yarn start. I get this error:

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
 6 | 
 7 | componentDidMount() {
 8 |   fetch('/users')
 9 |     .then(res => res.json()) <--
10 |     .then(users => this.setState({ users }));
11 | }
12 | 
2
  • Are your react app and your node app running on the same port? If not you will have to run them on the same port or through a reverse proxy Commented Jun 19, 2018 at 6:01
  • Yes I even tried to use 3001 in my users.js and added a proxy in my package.json to be 3001. Also, here's how my firebase database looks like: link Commented Jun 19, 2018 at 6:07

1 Answer 1

1

Take a snapshot of database using below function

var ref = db.ref("server/saving-data/fireblog/posts");

// Attach an asynchronous callback to read the data at our posts reference
ref.on("value", function(snapshot) {
  console.log(snapshot.val());
}, function (errorObject) {
  console.log("The read failed: " + errorObject.code);
});

Ref : https://firebase.google.com/docs/database/admin/retrieve-data

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.