![](/img/trans.png)
[英]AWS Access to XMLHttpRequest at from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header
[英]CORS BLOCKED 'Access-Control-Allow-Origin' Firebase Functions not allowed
向firebase
數據庫發送數據時出錯:
從來源“ http://localhost:3030 ”訪問“ https://us-central1-pwagram-f39a5.cloudfunctions.net/storePostData ”已被 CORS 策略阻止:對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”header。 如果不透明響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源
在部署到cors
后更改終點時,我遇到了這個問題firebase
。 但是在本地主機上運行時只有一個錯誤。 我需要它在本地主機上工作,因為我仍在使用它進行開發。
首先,我運行: npm install firebase-admin cors --save
這是我在文件夾firebase上的firebase
函數:
{
"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
}
這是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,
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});
});
});
});
這是我的sw.js function,它使用 function firebase
,但不工作:
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);
});
}
})
);
}
});
當我用正常的 firebase 數據庫鏈接.json
更改https://myFirebaseFUnctionLink/storePostData時,它的工作正常。
這個錯誤出現在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)
我有同樣的問題。 重點是 cors 方法的語法。 它需要 3 個參數:req、res、一個函數
return cors(req, res, function () { admin .database() .ref('posts') .push(req.body) .then(function () { return res.status(201).json({ message: 'Data stored', id: req.body.id, }); }) .catch(function (err) { return res.status(500).json({ error: err, }); }); });
我也遇到了這個問題,確切的錯誤措辭。 我使用 gsutil 更新了我的存儲 cors.json 設置,我將雲控制台中的單個函數權限更新為“允許未經身份驗證”,我什至在 index.ts 中將 cors 標頭添加到我的函數響應中——這些都沒有幫助。
解決方案:我的 firebase 應用程序需要啟用計費/升級到 Blaze 計划。 這立即解決了它。
我有同樣的問題,你必須進入“functions”文件夾中的“.eslintrc.json”並評論或刪除這一行:
"promise/always-return": 2,
之后,您不需要總是在 then 塊中添加 return ,因此刪除 return 關鍵字,如下所示:
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 });
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.