将数据发送到 firebase
数据库时出现错误:
在部署到 firebase
后使用 cors
更改端点时出现此问题。但是在本地主机上运行时只有一个错误。我需要在本地主机上使用它,因为我仍在使用它进行开发。
首先,我运行: npm install firebase-admin cors-保存
这是我的 package.json 在文件夹 firebase $ c $中c>函数:
{
name: functions,
description: Firebase的云功能,
脚本:{
lint: eslint。,
serve: firebase仅提供服务功能,
shell: firebase functions:shell,
start: npm run shell,
deploy: firebase deploy --only functions,
logs: firebase函数:log
},
engines:{
node: 8
},
dependencies:{
cors: ^ 2.8.5,
firebase-admin: ^ 8.9.1,
firebase-functions: ^ 3.3.0
},
devDependencies:{
eslint: ^ 5.12.0,
eslint-plugin-promise: ^ 4.0.1,
firebase-功能测试: ^ 0.1 .6
},
private:真
}
这里是 index.js 文件,我需要使用cors模块:
var functions = require('firebase-functions');
var admin = require('firebase-admin');
const cors = require(’cors’)({origin:true});
exports.storePostData = functions.https.onRequest(function(request,response){
return cors(function(request,response){
admin.database()。ref('posts')。push({
id:request.body.id,
title:request.body.title,
位置:request.body .location,
图片:request.body.image
})
.then(function(){
return response.status(201).json({message:'Data存储的,id:request.body.id});
})
.catch(function(err){
return response.status(500).json({error:err} );
});
});
});
这是我的 sw.js 函数,该函数使用函数 firebase
,但不起作用:
self.addEventListener(' sync',function(event){
console.log('[[Service Worker]后台同步',event);
if(event.tag ==='sync-new-posts'){
console.log('[[Service Worker] Syncing new Posts');
event.waitUntil(
readAllData('sync-posts')
.then(function(data){
用于(数据的dt数据){
fetch('https:// myFirebaseFUnctionLink / storePostData',{
方法:'POST',
标头:{
'Content-Type':'application / json',
'Accept':'application / json'
},
正文:JSON.stringify({
id:dt。 id,
标题:dt.title,
位置:dt.location,
图片:'https:// myfireba selink /’
}}
})
.then(function(res){
console.log('Sent data',res);
if(res.ok){
deleteItemFromData('sync-posts',dt.id); //工作不正常!
}
})
.catch(function(err){
console.log(发送数据时出错,err);
});
}
})
);
}
});
当我更改与常规firebase数据库链接 .json
正常工作。
此错误发生在 firebase
函数中:
TypeError:无法读取/srv/node_modules/cors/lib/index.js处未定义
的属性'origin':optionsCallback(/srv/node_modules/cors/lib/index.js处的219:40
:199:9)corsMiddleware(/srv/node_modules/cors/lib/index.js:204:7)中的
/srv/index.js:9:9中的
cloudFunction中的
(/srv/node_modules/firebase-functions/lib/providers/https.js:49:9)
在/worker/worker.js:783:7
在/worker/worker.js:766 :11
在_combinedTickCallback(内部/进程/next_tick.js:132:7)
在process._tickDomainCallback(内部/进程/next_tick.js:219:9)
我遇到了同样的问题,
您必须输入 .eslintrc.json在功能中文件夹并注释或删除以下行:
承诺/总是返回:2,
之后,您不必总是在then块中添加return,因此可以在其中删除return关键字:
const函数= require('firebase-functions');
const admin = require('firebase-admin');
const cors = require(’cors’)({origin:true});
// //创建和部署您的第一个云函数
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
const serviceAccount = require('./ serviceAccountKey.json');
admin.initializeApp({
凭证:admin.credential.cert(serviceAccount),
数据库URL:'https://you-project-addres.firebaseio.com/' ,
});
exports.storePostData =函数.https.onRequest((请求,响应)= >> {
return cors(request,response,()= >> {
admin
.database()
.ref('posts')
.push({
id:request.body.id,
title:request.body.id,
位置:request.body.location,
图像:request.body.image,
})
.then(()=> {
response.status (201).json({消息:已存储数据,id:request.body.id});
})
.catch((err)=> {
响应。 status(500).json({错误:err});
});
});
});
I had an error when sending data to a firebase
database :
I had this issue when changing the end point using cors
after deploying to firebase
. But the there is only an error when running on localhost. I need this to work on localhost because I am still using it for development.
First, I run: npm install firebase-admin cors --save
Here is my package.json on folder firebase
functions:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"cors": "^2.8.5",
"firebase-admin": "^8.9.1",
"firebase-functions": "^3.3.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.1.6"
},
"private": true
}
Here is index.js file i am require cors module:
var functions = require('firebase-functions');
var admin = require('firebase-admin');
const cors = require('cors')({origin: true});
exports.storePostData = functions.https.onRequest(function(request, response) {
return cors(function(request, response) {
admin.database().ref('posts').push({
id: request.body.id,
title: request.body.title,
location: request.body.location,
image: request.body.image
})
.then(function() {
return response.status(201).json({message: 'Data stored', id:request.body.id});
})
.catch(function(err) {
return response.status(500).json({error: err});
});
});
});
Here is my sw.js function that uses the function firebase
, but is not working:
self.addEventListener('sync', function(event) {
console.log('[Service Worker] Background syncing', event);
if (event.tag === 'sync-new-posts') {
console.log('[Service Worker] Syncing new Posts');
event.waitUntil(
readAllData('sync-posts')
.then(function(data) {
for (var dt of data) {
fetch('https://myFirebaseFUnctionLink/storePostData', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
id: dt.id,
title: dt.title,
location: dt.location,
image: 'https://myfirebaselink/'
})
})
.then(function(res) {
console.log('Sent data', res);
if (res.ok) {
deleteItemFromData('sync-posts', dt.id); // Isn't working correctly!
}
})
.catch(function(err) {
console.log('Error while sending data', err);
});
}
})
);
}
});
When I change https://myFirebaseFUnctionLink/storePostData with normal firebase database link .json
its work fine.
This error occurs in the firebase
function :
TypeError: Cannot read property 'origin' of undefined
at /srv/node_modules/cors/lib/index.js:219:40
at optionsCallback (/srv/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/srv/node_modules/cors/lib/index.js:204:7)
at /srv/index.js:9:9
at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:49:9)
at /worker/worker.js:783:7
at /worker/worker.js:766:11
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickDomainCallback (internal/process/next_tick.js:219:9)
解决方案 I had the same problem,you have to go in ".eslintrc.json" in "functions" folder and comment or remove this line:
"promise/always-return": 2,
after that, you don't need to always add return in then blocks so remove the return keywords there like this:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
const serviceAccount = require('./serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://you-project-addres.firebaseio.com/',
});
exports.storePostData = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
admin
.database()
.ref('posts')
.push({
id: request.body.id,
title: request.body.id,
location: request.body.location,
image: request.body.image,
})
.then(() => {
response.status(201).json({ message: 'Data stored', id: request.body.id });
})
.catch((err) => {
response.status(500).json({ error: err });
});
});
});
这篇关于不允许CORS阻止“访问控制允许起源” Firebase功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!