I am getting an error status code 404 while calling a function locally in nodejs server through firebase serve command.
My schedule.js file
const scheduleOfScheduledQuiz = async (req, res) => {
try {
const data = await getScheduledData();
return res.status(200).json({
message: "Scheduled for today:- ",
data: data
})
} catch (error) {
console.log("erro", error);
return res.status(500).json({
message: "Something went wrong....!!!"
})
}
}
module.exports = {
scheduleOfScheduledQuiz
}
getScheduledData() is a function which gets some data from the firebase realtime database
My index.js file
const functions = require("firebase-functions");
const app = require("express")();
//path to scheduleOfScheduledQuiz() function file
const scheduleOfScheduledQuiz = require("./handlers/Quiz/Scheduled_Quiz/scheduler");
app.get("*/scheduled-quiz/schedule/", scheduleOfScheduledQuiz.scheduleOfScheduledQuiz);
exports.api = functions.runWith({
memory: '2GB',
timeoutSeconds: '60'
}).https.onRequest(app);
So the error what i am getting :-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /predicta-6e51d/us-central1/api/scheduled-quiz/schedule/%0A</pre>
</body>
</html>
with status code 404
My package.json file
Global node js version - 12
firebase node js version - 10
"express": "^4.17.1",
"firebase": "^7.15.0",
"firebase-functions": "^3.7.0",
I am running this function locally on my nodejs server through firebase serve command.
NOTE:- when i am trying to run the same function on some other file it is perfectly running but not in this file.
Please Help
Thank You
Related
I have deployed the express app on vercel, other api are working fine but uploading image one is giving the error "Internal Server Error"
upload api in index.js
app.post("/api/upload", upload.single("file"), async (req, res) => {
res.status(200).json("File has been uploaded");
});
multer configuration
const multerStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./images");
},
filename: (req, file, cb) => {
cb(null, req.body.name);
},
});
const upload = multer({ storage: multerStorage });
I am trying in postman by entering the form data which includes name and file but if I try with only uploading file in binary, it is getting successful.
Path is fine, api is working smoothly in local but dont know why it is not working after deploying.
Github repo - https://github.com/JavaKaran/techducant-backend
Edit - 1
Error (getting in postman)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Internal Server Error</pre>
</body>
</html>
Edit - 2
vercel error for upload api
[POST] /api/upload
2022-12-14T15:52:55.912Z 0988f1fa-ba5c-49b8-ae08-889cc67e7889 ERROR Error: EROFS: read-only file system, open 'images/virtual.jpg'
I was creating a Node App using Express JS. There's a route which accepts a POST Request. The app works fine on localhost, but when I host on Cpanel Shared Hosting, I get the following error for POST request. GET works fine. Can anyone please help or guide where I went wrong?
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v1/email</pre>
</body>
</html>
My Express JS code
var app = express();
var em =require('./mailjet')
var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.get('/v1', function (req, res) {
return res.json('Hello World');
})
app.post('/v1/email', function (req, res) {
let {name, email, message}=req.body
if (!name || !email || !message){
return res.status(400).send({
'Message':'Bad Request'
})
}
em.request(name, email, message)
return res.status(200).send({
'Message':'Email Sent'
});
})
app.listen()
I am trying to deploy a nodeJS app on firebase using this tutorial "https://www.youtube.com/watch?v=LOeioOKUKI8&t=437s", I followed exactly what was told and the app worked as intended locally using "firebase serve" but when I deployed it, POST and GET request stopped working i.e. client side code is unable to reach server side.
for example, on loading "appURL/temp" I'm getting "Content Security Policy: The page’s settings blocked the loading of a resource" error.
What I'm actually trying to do : to send JSON data from Client to server, process the data and return some result as response
What currently app does: takes input, sends it to the server on click and receive it back as response to the POST request
on Client Side (public/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script defer src="/__/firebase/7.14.6/firebase-app.js"></script>
<script defer src="/__/firebase/init.js"></script>
</head>
<body>
<h1>Home</h1>
<input type="text" id="ip">
<button onclick="send()">send</button>
<div id="text"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
let textDiv = document.getElementById("text")
function send(){
let ip = document.getElementById("ip").value;
axios.post('/home',ip)
.then( resp => {
textDiv.innerHTML = JSON.stringify(resp.data);
})
}
</script>
</body>
on Server Side (functions/index.js
const func = require('./add'); //this is just to wrap the string with brackets
const functions = require('firebase-functions');
const express = require('express');
const multer = require('multer');
const upload = multer();
const app = express();
app.get('/temp', (req, resp) => {
resp.send("GET Works");
console.log("GET");
})
app.post('/home', upload.single("data"), (req, res) => {
console.log(func.add(JSON.stringify(req.body)))
res.send(func.add(JSON.stringify(req.body)))
});
exports.app = functions.https.onRequest(app);
firebase.json
{
"hosting": {
"public": "public",
"rewrites":[{
"source": "**",
"function": "app"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
Directory Structure
Versions
node : 13.6.0
express : 6.13.4
mutler : 6.13.4
I am building an app similar to amazon using:
expo and react-native
aws-amplify
I want to be able to print shopping cart using Expo Print API (imagine with the app, click the "print" button prints all items from your shopping cart into a pdf). The Print API takes a HTML string as input.
There are 2 ways to generate a HTML for the shopping cart: First, hardcode it in a javascript string. This approach is painful and too old school.
const html = cart => `
<!doctype html>
<html lang="en">
<head>
...
</head>
<div>
<h1>${cart.name}</h1>
...
</div>
`
Or utilize some tool to convert a (much easier to write) react component to a HTML - react-dom-server looks the right tool. However, react-dom-server can only be used in server side instead of client side, so I try to leverage lambda function that integrates well with aws-amplify.
These are what I tried:
add amplify function
$ amplify function add
Using service: Lambda, provided by: awscloudformation
? Provide a friendly name for your resource to be used as a label for this category in the project: renderReact
? Provide the AWS Lambda function name: renderReact
? Choose the function template that you want to use: Serverless express function (Integration with Amazon API Gateway)
? Do you want to access other resources created in this project from your Lambda function? No
? Do you want to edit the local lambda function now? Yes
Please edit the file in your editor: /Users/evan/source/inventoryapp-mobile/amplify/backend/function/renderReact/src/index.js
? Press enter to continue
Successfully added resource renderReact locally.
edit amplify/backend/function/renderReact/src/app.js
import React from "react";
import ReactDOMServer from 'react-dom/server';
var express = require("express");
var bodyParser = require("body-parser");
var awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");
// declare a new express app
var app = express();
app.use(bodyParser.json());
app.use(awsServerlessExpressMiddleware.eventContext());
// Enable CORS for all methods
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.get("/render", function(req, res) {
const reactDom = ReactDOMServer.renderToString(<div>hello world</div>);
res.json({ success: htmlTemplate(reactDom), url: req.url });
});
function htmlTemplate(reactDom) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React SSR</title>
</head>
<body>
<div id="app">${reactDom}</div>
</body>
</html>
`;
}
app.listen(3000, function() {
console.log("App started");
});
// Export the app object. When executing the application local this does nothing. However,
// to port it to AWS Lambda we will create a wrapper around that will load the app from
// this file
module.exports = app;
edit amplify/backend/function/renderReact/src/package.json
{
"name": "renderReact",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"aws-serverless-express": "^3.3.5",
"body-parser": "^1.17.1",
"express": "^4.15.2",
"react": "^16.10.1",
"react-dom": "^16.10.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
cd amplify/backend/function/renderReact/src && yarn install
edit amplify/backend/function/renderReact/src/event.json
{
"httpMethod": "GET",
"body": "{\"name\": \"Amplify\"}",
"path": "/render",
"resource": "/{proxy+}",
"queryStringParameters": {}
}
cd back to project root, run function but err
$ amplify mock function renderReact
Using service: Lambda, provided by: awscloudformation
? Provide the name of the script file that contains your handler function: index.js
? Provide the name of the handler function to invoke: handler
? Provide the relative path to the event: event.json
Testing function locally
/Users/evan/source/inventoryapp-mobile/amplify/backend/function/renderReact/src/app.js:24
const reactDom = ReactDOMServer.renderToString(<div>hello world</div>);
^
SyntaxError: Invalid or unexpected token
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
Note that I am not trying to render my <ShoppingCart /> component, just try to render the simplest <div>hello world</div> react component but no luck.
Any help? Thanks.
I am making an ultra simplistic site using the new-ish module tags inside the html file I serve from node. I have the latest version of chrome.
My node js function: (appController)
exports.getMainPage = (req, res) => {
res.writeHead(200, {'Content-type': 'text/html'});
fs.readFile('./public/views/index.html', null, (err, data) => {
if (err) console.error(err);
else res.write(data);
res.end();
});
};
I'm using express:
const express = require('express');
const router = express.Router();
const appController = require('../appController');
router.get('/', appController.getMainPage);
module.exports = router;
The html file:
<html lang="eng">
<head>
<script type="module">
import { $, $$ } from '../javascript/modules/bling';
</script>
<title>Logs</title>
</head>
<body>
</body>
</html>
Webstorm confirms that the path is fine but the console keeps showing:
GET http://localhost:7777/javascript/modules/bling net::ERR_ABORTED 404 (Not Found)