嗨,我在实时外部网址上使用Firebase托管应用时遇到问题。这是一个简单的聊天应用程序。它具有express,firebase函数,并且前端具有纯html和jquery。我无法获取数据以传输到我的应用程序或从中保存数据。在邮递员中,它工作正常。这是我的服务器:
// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');
var express = require('express')
const cors = require("cors");//({origin: true});
var bodyParser = require('body-parser')
var app = express()
var http = require('http').Server(app)
var io = require('socket.io')(http)
const firebase = require('firebase');
const admin = require('firebase-admin');
const firebaseConfig = {
apiKey: "ZY",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "t.com",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
var db = admin.firestore();
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//app.use(cors({origin: 'https://.firebaseapp.com'}));
//app.use(cors({origin: 'null'}));
app.use(require('cors')({origin: true}));
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
//mongoose.Promise = Promise
//var dbUrl = 'ue&w=majority'
//var Message = mongoose.model('Message', {
// name: String,
// message: String
//})
//
app.get('/messages', (req, res) => {
db.collection('users').get()
.then((snapshot) => {
debugger
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
//res.send(doc.id, '=>', doc.data())
//res.send(doc.data().name)
res.send(doc.data())
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
})
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
exports.getMessages = functions.https.onRequest((req, res) => {
// Forbidding PUT requests.
if (req.method === 'PUT') {
return res.status(403).send('Forbidden!');
}
// [END sendError]
return cors(req, res, () => {
db.collection('users').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
//res.send(doc.id, '=>', doc.data())
//res.send(doc.data().name)
res.send(doc.data())
});
})
.catch((err) => {
console.log('Error getting documents', err);
})
})
})
exports.addMessage = functions.https.onRequest((req, res) => {
try {
console.log('am bout to save this msg')
//save to firestore
//create new or overwrite docs
//const docRef = db.doc("users/Mu6BW6viq55faeiEXK0g")
//docRef.set({
// name: 'sample'
//});
//always add new documents
db.collection('users').add({
name: req.body
}).then(ref => {
console.log('Added document with ID: ', ref.id);
});
console.log('saved')
io.emit('message', req.body)
res.sendStatus(200);
} catch (err) {
res.sendStatus(500)
return console.error(err)
} finally {
//logger
console.log('message posted method called')
}
})
exports.addMessageTwo = functions.https.onRequest(async (req, res) => {
// [END addMessageTrigger]
// Grab the text parameter.
const formData = req.body;
// [START adminSdkAdd]
// Push the new message into Cloud Firestore using the Firebase Admin SDK.
const writeResult = await admin.firestore().collection('users').add({name: formData});
// Send back a message that we've succesfully written the message
res.json({result: `Message with ID: ${writeResult.id} added.`});
// [END adminSdkAdd]
});
io.on('connection', (socket) => {
console.log('a user connected')
})
//mongoose.connect(dbUrl, (err) => {
// console.log('mongo db connection', err)
//})
//var server = http.listen(3000, () => {
// console.log('server is listening on port', server.address().port)
//})
exports.api = functions.https.onRequest(app);
我的客户:
<!doctype html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@2/dist/socket.io.js"></script>
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.3.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script>
<div class="container">
<br>
<div class="jumbotron">
<h1 class="display-4">Send Message</h1>
<br>
<input id="name" class="form-control" placeholder="Name">
<br>
<textarea id="message" class="form-control" placeholder="Message"></textarea>
<br>
<button id="send" class="btn btn-success">Send</button>
</div>
<div id="messages">
</div>
<button id="do-query">Search</button>
</div>
<script>
$(document).ready(function() {
getMessages()
});
var socket = io()
$(() => {
$("#send").click(()=>{
console.log('about to send msg to postMessage()')
var message = { name: $("#name").val(), message: $("#message").val()};
console.log(message);
postMessage(message);
})
getMessages();
})
socket.on('message', addMessage)
function addMessage(message){
console.log(message)
$("#messages").append(`<h4> ${message.name.message} </h4> <p> ${message.name.name} </p>`)
}
$.ajaxSetup({
headers:{
'Content-Type' : "application/json",
'Access-Control-Allow-Origin:': "*"
}
});
function getMessages() {
$.get('https://us-central1-.cloudfunctions.net/getMessages', (data) => {
//data.forEach(addMessage(data));
console.log(data);
addMessage(data);
})
}
function postMessage(message) {
console.log('i made it into postMessage()')
$.post('https://us-central1-.cloudfunctions.net/addMessageTwo', message)
}
</script>
我可以通过所有导出功能通过Postman获取和发布数据。但是我前端的应用程序既不获取也不发布数据!我想念什么?我已经浏览了所有视频和教程!
只需使用简单的端点(例如$ .get('/ getMessages'))在localhost上正常工作就可以了。
这个奇怪的应用程序根本没有调用端点。没有Cors,没有问题。如上所述,在本地工作正常,但仅在已部署的客户端中调用==> Firebase Functions。 Firebase功能日志显示无呼叫。
可以帮忙吗?
谢谢