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 |