I use Firebase to host my nodejs application and use Cloud features.
Using the command firebase serve --only functions,hosting, I deploy my application.
I have a form with action="/putNPK"and works great when run from node.
But when I serve it through firebase, I get this error when I submit the form.
{"error":{"code":404,"status":"NOT_FOUND","message":"/putNPK is not a recognized path.","errors":["/putNPK is not a recognized path."]}}
How to fix it?
firebase.json looks like this: -
{
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "**",
"function": "app"
}
],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"trailingSlash": true
}
}
This is my folder structure: -

Content index.js: -
const admin = require("firebase-admin") ;
const express = require("express") ;
const app = require("express")() ;
const bodyparser = require("body-parser") ;
const functions = require("firebase-functions") ;
const request_controller = require("./requests_controller") ;
app.use(express.static('../public/assets/')) ;
app.use(express.static('../public/')) ;
request_controller(app) ;
app.use((req ,res , next)=>{
res.status(404).redirect('404.html') ;
})
app.listen(8000) ;
exports.app = functions.https.onRequest(app) ;
COntents of request_controller file (module imported into index.js): -
const admin = require("firebase-admin") ;
const bodyparser = require("body-parser") ;
const app = require("express")() ;
const urlencodedParser =bodyparser.urlencoded({extended : true}) ;
const posthandler = require("posthandler") ;
const gethandler = require("gethandler") ;
var serviceAccount = require("C:/Users/Natesh/Documents/raita-mitra-2018-firebase-adminsdk (acnt nateshmbhat1).json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://raita-mitra-2018.firebaseio.com"
});
function validatePostBody(req , res , keys ){
for(i in keys){
if(!(keys[i] in req.body))
{
console.log("invalid post request returning ! ") ;
return false ;
}
}
return true ;
}
module.exports = function Handle_requests(app)
{
console.log('Request Handler started ! ') ;
app.get('/' , (req , res)=>{
res.sendFile(__dirname + '/index.html') ;
})
app.get('/home' , (req , res)=>{
res.sendFile(__dirname + '/index.html') ;
})
app.post('/putNPK', urlencodedParser ,(req , res)=>{
if(!validatePostBody(req , res , ['fertilizer' ,'crop' , 'nitrogen' , 'phone' , 'phosphorus' , 'potassium'])) return ;
ref = admin.database().ref('/users/' + req.body.phone) ;
ref.set(req.body) ;
console.log("Added to firebase database") ;
res.status(200).redirect('/') ;
admin.messaging().sendToTopic('global' , {
notification : {
title : 'Farmer Project' ,
body : 'notification body'
} ,
data : {
nitrogen : req.body.nitrogen
}
})
} )
}