i try deployed a example in cloud functions for test and don't works, my code is:
`const functions = require('firebase-functions');
const Fastify = require('fastify')
const fastify = Fastify()
fastify.get("/",async (req, reply) =>{
reply.send({ hello: "world" })
})
fastify.listen(3000)
module.exports = { api: functions.https.onRequest(fastify) };`
Someone knows how deploy the server of fastify as express
this issue has been explained in Fastify some days ago.
You can check the full explanation here by maintainers
I'll post here the working solution:
const functions = require('firebase-functions')
const http = require('http')
const Fastify = require('fastify')
let handleRequest = null
const serverFactory = (handler, opts) => {
handleRequest = handler
return http.createServer()
}
const fastify = Fastify({serverFactory})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
exports.app = functions.https.onRequest((req, res) => {
req = Object.assign({ip: ''}, {...req});
fastify.ready((err) => {
if (err) throw err
handleRequest(req, res)
})
})
Related
For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};
I am developing an e-commerce website and as of now I have these basic backend codes:
const port = process.env.PORT || 5429
const express = require ('express')
const server = express ()
const cors = require('cors')
server.use (cors ())
const bodyParser = require('body-parser')
server.use (bodyParser.json ())
server.use (bodyParser.urlencoded ({ extended: true }))
server.listen (port, () => {
console.log (`Server port listening to: ${ port }`)
})
Now I am having trouble where to put the
const mysql = require ('mysql') together with mysql.createPool ({ ... }).
Should i put them here before the server.listen? or
Should I go with this?
module.exports = class Database {
connectWithPool () {}
}
and put is under here:
const Database = require ('./db.js')
const db = new Database ()
module.exports = class User {
login (req, res) {
....
db.connectWithPool ()
....
}
}
and attach the user.login in route
const User = require ('user.js')
const user = new User ()
module.exports = class Routes {
constructor (server) {
this.server = server
}
routeUser () {
this.server.post ('/api/user', user.login)
}
}
Your suggestions. Because its not very clear to me how createConnection and createPool works internally.
P.S: disregard if there's an error to my codes. I just want to explain my own idea.
I'm a new learner to express js and sequelizejs. I successfully migrate table in my database so the connection is fine I guess.
Here is my code.
https://github.com/Picks42/express-test
Please review this file
https://github.com/Picks42/express-test/blob/master/models/user.js
Then review this one
https://github.com/Picks42/express-test/blob/master/controller/test.js
Let me know what's the issue.
// all the models using your index.js loader
const models = require('../models');
// the user model, note the capital User since
const M_Bank = models.User;
exports.getTest = function(req,res){
return M_Bank
.findAll()
// don't use M_Bank here since you are getting an array of Instances of the Model
.then(users => res.status(200).send(users))
.catch((error) => {
console.log(error.toString());
res.status(400).send(error)
});
/* this will never execute because it is after the return
exports.index = function (request, response, next) {
response.json((M_Bank.findAll()));
};
*/
};
If you have the option of using async/await it makes for more readable code.
const models = require('../models');
const M_Bank = models.User;
exports.getTest = async function(req, res) {
try {
const users = await M_Bank.findAll();
return res.status(200).send(users);
} catch (err) {
console.log(err.toString());
return res.status(400).send(err);
}
};
You should get rid of the .User field in the 3rd line. because you've exported User itself from the models/user file.
Also, I recommend you not to mess with variables names. M_Bank variable doesn't speak itself
const M_Bank = require('../models/user');
exports.getTest = function(req,res){
return M_Bank
.findAll()
.then(M_Bank => res.status(200).send(M_Bank))
.catch((error) => {
console.log(error.toString());
res.status(400).send(error)
});
exports.index = function (request, response, next) {
response.json((M_Bank.findAll()));
};
};
the link to the project
https://github.com/Kammikazy/project
i can´t make work my get two or more methods in same route
i have the code 404
i using mysql nodejs and express
my code
controller alliances
const User = require('../models/Alliances')
const findAlianca = async (connection, req, res) => {
const Allianca = await User.find(connection, req.session.user.username)
if (!Allianca) {
res.status(404).send('Nenhuma cidade encontrada.');
return;
}
console.log("dddd");
req.session.Allianca = Allianca
res.locals.Allianca = Allianca
res.render('Administration/Alliances')
}
module.exports = {
findAlianca
}
route aliance
const express = require('express')
const router = express.Router()
const connection = require('../../Config/database')
const controllerAdmin = require('../../controllers/Administration')
const controlleruser = require('../../controllers/Alliances')
router.get('/Administration/Alliances', (req, res) => controllerAdmin.findcidade3(connection, req, res))
router.get('/Administration/Alliances/limitado', (req, res) => controlleruser.findAlianca(connection, req, res))
module.exports = app => app.use('/', router)
models aliance
const find = (connection,username) => {
return new Promise((resolve, reject) => {
connection.query(SELECT alianca.nome,alianca.N_membros,alianca.TAG FROM user INNER JOIN alianca ON user.cod_alianca=alianca.id WHERE user.username='${username}', (err, result) => {
if(err){
reject(err)
}else{
resolve(result)
}
})
})
}
module.exports = {
find
}
alliance.jade
extends layout
block title
.col-xs-6.col-xs-offset-3.col-sm-6.col-sm-offset-3
.col-sm-4(style='width:76%')
div.panel.panel-primary(style='height:50px') Alliances Page
div.panel.panel-primary(style='height:700px') fdssdklfsdklfjskldfjkldsjfl
if locals.user.cod_alianca==null
p You Dont Have Alliances
else
br
span Your Aliance
span= locals.Allianca.nome
.col-xs-2.panel-red(style='width:24%;height:100%;text-align:center')
my app
require('./routes/Administration/Alliances')(app)
my connection db
const mysql = require('mysql')
const config = require( "./config.json" )
const connection =mysql.createConnection({
host:config.host,
user:config.user,
password:config.password,
database:config.database,
// port:config.port
});
connection.connect((err) =>{
if(err){
console.log(err)
process.exit(0)
}else{
console.log('database on')
}
})
what i doing wrong i can´t find the solution for my problem
Not sure what you are asking however if you want to call multiple function in same route/API you can do following:
Using expressJs you can use next function like:
app.get('/Administration/Alliances', (req, res, next) => {
//Do something here and to add data to your request use
req.body.newData = 'newData';
//after this just call next function
next();
}, (req, res, next) => {
//Can continue this cycle of calling next function until last `sendResponse` function is reached.
//Can even set `error` in request for `sendResponse`
req.error = "Some error";
next();
}, (req, res) => {
if(req.error) {
res.status(400).send(req.error);
} else {
res.status(200).send(req.body.result);
}
});
the soluction for my problem
const express = require('express')
const router = express.Router()
const connection = require('../../Config/database')
const controllerAdmin = require('../../controllers/Administration')
const controlleruser = require('../../controllers/Alliances')
router.get('/Administration/Alliances', (req, res, next) => {
//Do something here and to add data to your request use
controllerAdmin.findcidade3(connection, req, res)
next();
}, (req, res, next) => {
//Can continue this cycle of calling next function until last `sendResponse` function is reached.
//Can even set `error` in request for `sendResponse`
controlleruser.findAlianca(connection, req, res)
})
module.exports = app => app.use('/', router)
I have the following node code,i am trying to query the database based on a request,i use sequelize orm with mysql
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axios = require("axios");
const models = require("./models");
const jsonParser = bodyParser.json();
app.post("/auth/change", jsonParser, (req, res) => {
let phoneNumber = req.body.phone;
let password = req.body.password;
console.log("phone number", phoneNumber);
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
console.log(user.name);
}).catch(error => {
console.log(error);
});
});
app.listen(3000, () => {
console.log("Listening on port 3000");
});
I use react on the front end, and when i send a request with data for example
{phone:777,password:123} it works, but if i do a second request with same or different data it fails.What am i missing here!!?
you are not returning any data to the front side when it call the API , so the server will be waiting to return a response to the caller.
try to change your code to this :
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
res.status(200).send('ok')
}).catch(error => {
res.status(400).send('not ok')
});