我已经编写了一些云函数并进行了部署,现在我正尝试使用Angular应用程序访问这些API,但出现此错误
从源’ http:// localhost:4200 ‘ 在’xxxxxxxxxxxxxxxxxxxxxxxx’处对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:没有’Access- Control-Allow-Origin’标头在请求的资源上。
我知道我必须在我的云功能中启用cors,但是我从来没有做过,如果你们能告诉我该怎么做,那将是很棒的吗?我确实检查了该线程,但是对于在哪里需要初始化cors以及是否也需要安装其依赖项以及在哪里需要在我的云函数中启用它,我有些困惑。这是我的云功能
const functions = require('firebase-functions'); const admin = require("firebase-admin"); const bodyParser = require("body-parser"); admin.initializeApp(); const db = admin.firestore(); const usersCollection = db.collection("users"); exports.addUser = functions.https.onRequest((req, res) => { if (req.body.username != null && req.body.firstname != null && req.body.lastname != null && req.body.addr1 != null && req.body.addr2 != null || req.body.username != undefined && req.body.firstname != undefined && req.body.lastname != undefined && req.body.addr1 != undefined && req.body.addr2 != undefined ) { let docId = Math.floor(Math.random() * (99999 - 00000)); let newUser = { "username": req.body.name, "firstname": req.body.firstname, "lastname": req.body.lastname, "addr1": req.body.addr1, "addr2": req.body.addr2, } usersCollection.add(newUser).then(snapshot => { res.send(200, { "message": "User was successfully created" }) }); } else { res.send(400, { "message": "All fields are required" }) } });
有两种解决方法
OPTIONS
科尔斯
从获取请求方法 headers
headers
检查方法是否 OPTIONS
使用200状态代码解析API 。
200
exports.addUser = functions.https.onRequest((req, res) => { res.set('Access-Control-Allow-Origin', '*'); res.set('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS'); res.set('Access-Control-Allow-Headers', '*'); if (req.method === 'OPTIONS') { res.end(); } else{ if (req.body.username != null && req.body.firstname != null && req.body.lastname != null && req.body.addr1 != null && req.body.addr2 != null || req.body.username != undefined && req.body.firstname != undefined && req.body.lastname != undefined && req.body.addr1 != undefined && req.body.addr2 != undefined ) { let docId = Math.floor(Math.random() * (99999 - 00000)); let newUser = { "username": req.body.name, "firstname": req.body.firstname, "lastname": req.body.lastname, "addr1": req.body.addr1, "addr2": req.body.addr2, } usersCollection.add(newUser).then(snapshot => { res.send(200, { "message": "User was successfully created" }) }); } else { res.send(400, { "message": "All fields are required" }) } } });