嚕嚕噠
2022-08-27 15:12:35
在我的客戶端javascript中,如果用戶獲得授權(quán)(使用firebase身份驗(yàn)證),我會請求私有內(nèi)容,如下所示:firebase.auth().onAuthStateChanged(user => { if (!user) { ui.start("#firebaseui-auth-container", uiConfig); } if (user) { import("/private.js").then(module => { console.log(module.default); }); }});所有用戶都通過托管網(wǎng)址的公共 firebase 提供服務(wù),但只有當(dāng)用戶獲得授權(quán)時,他們才會請求私有內(nèi)容。我的重定向來處理這個問題:index.htmlfirebase.json "rewrites": [ { "source": "**", "function": "app" } ]我正在努力建立一個基于firebase函數(shù)的express后端來為javascript服務(wù)。(我還沒有添加身份驗(yàn)證檢查,因?yàn)槲蚁胱屗ぷ?,只是先為js服務(wù))。我的 firebase 函數(shù)如下所示:const fs = require("fs");const functions = require("firebase-functions");const express = require("express");const app = express();app.get("/private.js", (req, res) => { fs.readFile("private.js", "utf8", function (err, data) { if (err) throw err; res.send(data) });});exports.app = functions.https.onRequest(app);但是,當(dāng)用戶獲得授權(quán)并且客戶端嘗試動態(tài)導(dǎo)入時,我收到以下錯誤:。如何正確設(shè)置MIME類型以提供js文件?private.jsFailed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec
3 回答

30秒到達(dá)戰(zhàn)場
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個贊
我解決了這個問題。我需要使用:
res.setHeader("Content-Type", "text/javascript"); //Solution! res.writeHead(200); res.end(data);
而且它工作正常。

一只甜甜圈
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個贊
您需要告訴瀏覽器發(fā)生了錯誤,以便它不會嘗試將響應(yīng)解析為JavaScript。您可以通過發(fā)送以 4(客戶端錯誤)或 5(服務(wù)器錯誤)開頭的狀態(tài)代碼來執(zhí)行此操作。下面是一個示例:
app.get("/private.js", (req, res) => {
fs.readFile("private.js", "utf8", function (err, data) {
if (err) {
res.status(403).send('Could not load the data.');
} else {
res.send(data);
}
});
});
添加回答
舉報
0/150
提交
取消