How to setup firebase for storage in nodejs? i did storage set in react but for some issuess i want to do that in nodejs so how can i do that in nodejs? it's giving me errors can anyone can tell me how to import properly to use that as a nodejs route
i have created a file called firebasestore for this how to import properly:
import firebase from 'firebase/compat/app';
import 'firebase/compat/storage';
const firebaseConfig = {
// here is everything for config
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
export { firebase };
Route where i want to use how to import properly:
router.post('/changeusername', (req, res) => {
const { Image } = req.body
if (!Image.cancelled) {
setIsPosting(true)
const response = await fetch(Image);
const blob = await response.blob();
const filename = Image.substring(Image.lastIndexOf('/') + 1);
const ref = firebase.storage().ref().child(filename);
const snapshot = await ref.put(blob);
const url = await snapshot.ref.getDownloadURL();
}
})
Related
Right now I'm tinkering with child_added and child_change as well as limittoLast() to properly understand how event listeners work and how I can extract the newly created value which in this case a new child node.
import * as functions from "firebase-functions";
import * as express from "express";
import * as cors from "cors";
import * as admin from "firebase-admin";
admin.initializeApp();
const bot = express();
bot.use(cors( {origin: true}));
bot.post("/", async function(req, res) {
const telegramText = req.body;
req.body.message &&
req.body.message.chat &&
req.body.message.chat.id &&
req.body.message.from &&
req.body.message.from.first_name;
if (telegramText) {
const chat_id = req.body.message.chat.id;
const first_name = req.body.message.from.first_name;
const receivedMessage = req.body.message.text;
// -NHi9ZWHVqTb-wJd9yh0N - test node
// Define your RTDB Reference
const rtdbReference = admin.database().ref("Sensor MQ7");
rtdbReference.on("child_added", callback =>{
console.log("MQ7", callback.val());
})
const mq7ref = rtdbReference.child("-NHi9IWHVqTb-wJd4yhN/MQ7");
mq7ref.orderByKey().limitToLast(1);
// Fetch the data
const snap = await mq7ref.get();
const snapValue = snap.val();
// Inject snapvalue in the response
return res.status(200).send({
method: "sendMessage",
chat_id,
text: `${first_name}\n${receivedMessage}\n${snapValue}`,
});
}
return res.status(200).send({status: "An error occured"});
});
export const router = functions.https.onRequest(bot);
This is the result of my experimentation and as of now I have very limited understanding of how everything works so I'm learning as I go.
According to my RTDB I'm trying to get latest child node whenever it's added
RTDB
Any help or suggestion is greatly appreciated and if possible, I'd like to request a sample code of where I could start working/repair as I'm very new to firebase as well as NodeJS.
My fetch takes too long until it fails
I tried chrome, edge and postman
other fetch requests from pixabay api are working great
I compared the code to other projects I've made and found nothing
I also added a proxy to "package.json" as suggested on some places and it didnt work
posting below parts of my code:
controller:
import axios from 'axios'
export const getAll = async () =>{
const response = await axios.get('https://pixabay.com/api/?key=25540812-faf2b76d586c1787d2dd02736')
.then(resp=>resp)
.catch(err=>console.log(err));
return response;
}
router:
import express from "express";
import * as homeController from '../controllers/home.controller.js'
const homeRouter = express.Router();
homeRouter.get('/all', homeController.getAll)
export default homeRouter
indexjs:
import express from "express"
import dotenv from "dotenv"
import homeRouter from './routers/home.router.js'
dotenv.config();
const PORT = 3000 //process.env.PORT
console.log(PORT);
const app = express();
app.use(express.json());
app.use(homeRouter)
app.listen(PORT, ()=>{console.log(`server is connected on port ${PORT}`)})
fetch:
const getAll = async()=>{
try {
const response = await fetch (`http://localhost:3000/all`)
console.log("hu");
if (!response.ok) {
throw new Error();
}
else{
console.log("ok");
}
const responseObj = await response.json();
console.log(responseObj);
}
catch (error) {
console.log(error);
}
}
useEffect(()=>{
getAll();
},[])
Posting the answer by #Jaromanda X for everyone to see:
"see this app.get('/', (req, res) => { ... where's you req and res ??? nowhere, that's where - hint: export const getAll = async (req, res) =>{"
Apparently EVERY controller made with express needs to send a response back (in the form of res.send)
Should be obvious but somehow I missed it
Thanks everyone!
the problem i'm having is basically my app works fine in local but in production anywhere that i've used server side rendering returns 500 internal server error. the other parts of my site which are called normally like in useEffect or componentDidMount work completely fine, like my dashboard or authorization process works without a problem, but anywhere that i have used ssr returns 500.
Below is some examples of how i have handled my ssr pages.
index page:
import React from 'react';
import HomePage from '../components/homePage/index'
import { Api, GuestHeaders } from '../components/config'
const Home = (props) => {
return <HomePage {...props} />
}
export async function getServerSideProps() {
const Response = await Api.get(`/v1/index`, { headers: GuestHeaders })
return {
props: {
Detail: Response.data,
}
}
}
export default Home
here is my Api component:
import axios from 'axios';
const GuestHeaders = {
'Authorization': "",
'content-type': 'application/json'
}
const Api = axios.create({
baseURL: 'baseUrl'
})
export { Api, GuestHeaders };
here is my server.js:
// server.js
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
// Be sure to pass `true` as the second argument to `url.parse`.
// This tells it to parse the query portion of the URL.
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
and my next.config.js:
module.exports = {
basePath: '',
trailingSlash: false,
}
I am trying to fetch a zip file uploaded to aws s3. After that file is fetched, I have to extract it and display the names of files inside the folder. How can I achieve this? I am new to file streaming and this is what I have done till now.
import * as aws from "aws-sdk";
import express from "express";
import fs from "fs";
import request from "request";
import * as unzipper from "unzipper";
const config = {
// credentials
};
const s3Client = new aws.S3(config);
const app = express();
app.use(express.json({
limit: "1mb"
}));
app.use(express.urlencoded({
extended: true
}));
app.post("/seturl", async(req, res) => {
try {
const url = req.body.url;
request(url).pipe(fs.createWriteStream('ez.zip'));
console.log("here");
const zip = fs.createReadStream('ez.zip').pipe(unzipper.Parse({
forceStream: true
}));
for await (const entry of zip) {
const fileName = entry.path;
console.log("///////////", fileName);
const type = entry.type; // 'Directory' or 'File'
const size = entry.vars.uncompressedSize; // There is also compressedSize;
if (fileName === "this IS the file I'm looking for") {
entry.pipe(fs.createWriteStream('output/path'));
} else {
entry.autodrain();
}
}
} catch (error) {
return Promise.reject(`Error in reading ${error}`);
}
});
app.listen(5600, (err) => {
if (err) {
console.error(err);
} else {
console.log("running");
}
});
I am using the unzipper library here. If there is something better, I am open to use it. As of now, I am getting FILE ENDED error.
If I send POST such /image/cover or /image/sub/ from client, the router function doesn't work at all so It sends 404. It's supposed to work but I literally have no idea. I never had this case It just doesn't work for no reason.
router
import Router from 'koa-router'
const router = new Router({ prefix: '/image' })
router.post('/cover', async (ctx, next) => {
let URLpath = ctx.request.body.files.cover.path
ctx.body = { url: URLpath }
})
router.post('/sub', async (ctx, next) => {
let URLpath = ctx.request.body.files.sub.path
ctx.body = { url: URLpath }
})
export default router
log
<-- POST /image/cover
--> POST /image/cover 404 33ms -
import code (UPDATED)
router/index.js
import compose from 'koa-compose'
import accountRouter from './account'
import mypageRouter from './mypage'
import imageRouter from './image'
import postRouter from './post'
const routes = [
accountRouter,
mypageRouter,
imageRouter,
postRouter
]
export default () => compose([].concat(
...routes.map(r => [r.routes(), r.allowedMethods()])
))
app.js
import Koa from 'koa'
import serve from 'koa-static'
import logger from 'koa-logger'
import views from 'koa-views'
import session from 'koa-session'
import passport from 'koa-passport'
import bodyParser from 'koa-body'
import path from 'path'
import routes from './routes'
import config from './config'
import form from './util/formidable'
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose
.connect(config.MONGODB_URI)
.then(startApp).catch(::console.error)
function startApp() {
const app = new Koa()
const port = process.env.PORT || 3000
const dist = __dirname + '/views/'
console.log(form)
const bpOption = { IncomingForm: form, multipart: true }
app.keys = ['secret', 'key'];
require('./util/passport')
app
.use(logger())
.use(serve(dist))
.use(session({}, app))
.use(bodyParser(bpOption))
.use(passport.initialize())
.use(passport.session())
.use(views(__dirname+'/views', { extension: 'pug'}))
.use(routes())
app.listen(port, () => console.log(`[!] Server is Running on ${port}`))
}
you need help function:
// #help function record route table map
'use strict';
const fs = require('fs');
const resolve = require('path').resolve;
module.exports = function record(router, filename) {
const routeTable = fs.createWriteStream(resolve(__dirname, filename));
routeTable.write(`Update Date: ${new Date().toString()}\n\n`);
for (let len = router.stack.length, i = 0; i < len; i += 1) {
const route = router.stack[i];
routeTable.write(`URL:${route.path}\t${route.methods.join('|')}\n`);
}
routeTable.end();
};
then you can involve it by
const record = require('./record');
record(routeApp, '.routerc')
you will get .routerc file(route map) with content such as:
URL: /a/c/c POST
URL: /b/a/d GET
it can help you to solve problem. maybe work. good luck!