【发布时间】:2020-11-03 02:07:32
【问题描述】:
对 firebase 非常陌生,并且在代码方面非常初级。我试图找出一个错误,即没有显示自定义 404,或者当重写更改时应用程序无法工作。
"rewrites": [
{
"source": "**",
"function": "app"
}
]
这会将所有内容重定向到应用程序并且应用程序功能正常。但是,如果尝试了错误的 URL,404.html 不会显示。有一个通用的“Cannot GET /asdfasd”
改成
"rewrites": [
{
"source": "/",
"function": "app"
}
]
现在将正确显示自定义 404.html。
但是,使用此配置的函数会以 404 响应,从而破坏应用程序。来自函数/index.js:
app.post('/sendsmstoconsumer', (request, response) => {
client.messages
.create({body: request.body.message, from: '+15555555555', to: request.body.phone})
.then(message => {
response.send("Your message: " + request.body.message + " has been sent!")
});
})
我已经尝试了一些类似下面的变体,但我只是错过了一些东西。
{
"source": "/",
"function": "app"
},
{
"source": "/sendsmstoconsumer",
"function": "sms"
}
]
更改函数/index.js:
exports.sms = functions.httpsOnRequest((request, response) => {
client.messages
.create({body: request.body.message, from: '+15555555555', to: request.body.phone})
.then(message => {
response.send("Your message: " + request.body.message + " has been sent!")
});
})
如果能以正确的方式构建重写或更改自定义 404 和应用程序正常工作的功能,我将不胜感激。我似乎无法选择其中一个。
谢谢。
根据要求,编辑以添加完整的文件:
firebase.json
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "app"
}
]
},
"emulators": {
"functions": {
"port": 5001
},
"database": {
"port": 9000
},
"hosting": {
"port": 5000
},
"ui": {
"enabled": true
}
}
}
index.js
const functions = require('firebase-functions')
const express = require('express')
const app = express()
const accountSid = 'xxx'
const authToken = 'xxx'
const client = require('twilio')(accountSid, authToken)
const cors = require('cors')
// Enable cors for everything
// TODO: Re-enable cors at a later date
// src: https://www.npmjs.com/package/cors
app.use(cors())
app.post('/sendsmsverificationmessage', (request, response) => {
client.verify.services('xxx')
.verifications
.create({to: request.body.phone, channel: 'sms'})
.then(verification => {
response.send("Your verification code has been sent to your phone!" )
});
})
app.post('/verifyusersphonenumber', (request, response) => {
client.verify.services('xxx')
.verificationChecks
.create({to: request.body.phone, code: request.body.token})
.then(verification_check => {
response.send("Your phone has been verified!")
});
})
app.post('/sendsmstoconsumer', (request, response) => {
client.messages
.create({body: request.body.message, from: '+15555555555', to: request.body.phone})
.then(message => {
response.send("Your message: " + request.body.message + " has been sent!")
});
})
exports.app = functions.https.onRequest(app)
【问题讨论】:
-
你是如何向函数发出请求的?请编辑问题以端到端显示所有代码。
-
@DougStevenson 我已按要求添加。函数请求是通过 POST 到 //my.web.app/sendsmstocustomer 的,它与上面添加的文件一起使用,但不提供 404.html。
标签: firebase google-cloud-functions