我得到错误:
Access to XMLHttpRequest at 'https://us-central1-myproject-64732.cloudfunctions.net/getProduct has been blocked by CORS
我的域注册为example.com
。
编辑
我有:
const cors = require('cors')({origin: true});
const rp = require('request-promise');
exports.getProduct = functions.https.onRequest((request, response) => {
const options = {
uri: url,
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': '*',
'Accept-Language': 'en-US,en',
"Access-Control-Allow-Origin":"*",
'Access-Control-Allow-Methods': 'GET, PUT, POST, OPTIONS',
'Access-Control-Allow-Headers': '*',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Referer': 'http://www.google.com/',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
rp(options)
.then(($) => { ...
我的Access-Control-Allow-Origin
在那里,而错误显示未显示。
EDIT2
该功能在本地机器和终端模拟器上使用时有效,但在浏览器中不起作用。
这样尝试:
import * as functions_ from 'firebase-functions';
// import * as firebaseHelper from 'firebase-functions-helper';
import * as express_ from 'express';
import * as bodyParser_ from "body-parser";
import News from './news.function';
import Meteo from './meteo.function';
const _cors = require('cors')({
origin: true,
});
let bodyParser = bodyParser_;
let express = express_;
let functions = functions_;
// const db = admin.firestore();
const app = express();
const main = express();
// YOUR API ROUTES
app.get('/news/', (req, res) => News(req, res));
app.get('/meteo/', async (req, res) => {
console.log('here');
Meteo(req, res)
});
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
// webApi is your functions name, and you will pass main as
// a parameter
export const webApi = functions.https.onRequest((req, resp) => {
_cors(req, resp, () => {
main(req, resp);
})
});
希望它能帮助你!!
对于任何正在挣扎的人,我找到了一个解决方案。
exports.getProduct = functions.https.onRequest((request, response) => {
cors(request, response, () => { // ****** thats solve it
const options = {
uri: url,
headers: { ......
rp(options)
.then(($) => { ...
添加cors请求使其工作。当然包括图书馆。我还发现,当我部署单个函数时,它不会总是部署它,或者会产生一些奇怪的问题。