我无法连接我连接的node.js后端代码,当它们在后端运行时工作正常,但是当我尝试在前端使用这些函数时react.js它没有工作。我收到意外令牌的错误,我认为是因为它取错了数据。
这是我的后端桌面\ 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包含我的firebase信息。我把X放在这里只是为了显示它。
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"
};
这是我的前端桌面\ 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;
它不是从数据库中获取数据,我在运行纱线启动时甚至无法编译它。我收到这个错误:
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 |
答案 0 :(得分:1)
使用以下功能拍摄数据库快照
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);
});
参考:https://firebase.google.com/docs/database/admin/retrieve-data