koa js async await not working when used with ajax and promise - koa

I'm using koa as a rest backend but I can't get the routing and request/response to work properly, when the URL is called using axios the promise is failing.
server.js
const route = require('koa-route');
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const path = require('path');
const bodyParser = require('koa-bodyparser');
const Datastore = require('nedb'),
db = new Datastore({
filename: __dirname +'/storage.db' ,
autoload: true
});
// something
app.use(bodyParser());
app.use(serve(__dirname + '/dist'));
app.use(route.get('/api/projects', async function (next) {
let projects = [];
await db.find({}, function (err, docs) {
projects = docs;
});
this.body = projects;
}));
const PORT = process.argv[2] || process.env.PORT || 3000;
app.listen(3000);
when I make a request to /api/projects using axios I get and empty array
from my package.json
"scripts": {
"start": "nodemon server.js --exec babel-node --presets es2015,stage-2"
},

You're mixing promises with callbacks, which is most likely causing your problems.
Stick to using promises:
app.use(route.get('/api/projects', async function (next) {
let projects = await db.find({});
this.body = projects;
}));

Related

Serve static image using netlify?

I am currently using express and I want to host my website with netlify but the problem is I don't know how to serve static images with netlify. While normally running the app not using netlify everything works. Is there a way to serve static images while hosting nodejs app on netlify ?
const express = require("express");
const serverless = require("serverless-http");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Header", "Content-Type, Authorization");
next();
});
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.use("/images", express.static(path.join(__dirname, "images")));
const rootDir = require("./util/path");
const errorController = require("./controllers/error");
const projectRoutes = require("./routes/project");
const { json } = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/.netlify/functions/app", projectRoutes);
module.exports.handler = serverless(app);
Folder Structure

Express server not running when using ng serve

My server.js is not getting executed when I use ng serve command from angular-cli. When I use node server, it works fine.
server.js:
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path');
const http = require('http');
const api = require('./server/routes/api');
const port = 3000;
const app = express();
app.use(express.static(path.join(__dirname, 'dist/Colab')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/api', api);
app.get('*', (req,res)=>{
res.sendFile(path.join(__dirname, 'dist/Colab/index.html'));
});
const server = http.createServer(app);
server.listen(port, ()=>console.log(`Server is running on localhost:${port}`));
Try using the following commands:
npm start
OR
node app.js

Display image on pug

I'm new to NodeJS world.
I tried to display image from mongodb using pug and node express.
Please see my code and guide me.
customer.pug
extend layouts
block content
h1.container #{title} of #{customer.full_name}
div.container
p Full Name: #{customer.full_name}
p Address: #{customer.address}
p Age: #{customer.age}
img.imageScr1(src=customer.profileimage, alt=customer.full_name)
app.js
const express = require('express');
const path = require('path');
const router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
// set storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './uploads/',)
},
filename: function (req, file, cb) {
cb(null, file.fieldname + Date.now() + path.extname(file.originalname));
}
});
// init upload
const upload = multer({
storage: storage
});
// Middlewares
// middleware for Assets - to set public for assets
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// route - homepage
app.get('/', function (req, res) {
Customer.find({}, null, function(err, customers) {
if(err){
console.log(err);
} else{
// customers.profileimage = '/' + customers.profileimage;
// console.log('image prefix::: ' + customer.profileimage);
res.render('index', {
title: 'Customer List',
customers: customers
});
}
});
});
app.post('/customer/add', upload.single('profileimage'), function (req, res) {
var customer = new Customer();
customer.full_name = req.body.full_name;
customer.address = req.body.address;
customer.age = req.body.age;
customer.profileimage = req.file.path;
customer.save(function (err) {
if(err){
console.log(err);
} else{
res.redirect('/');
}
});
});
I got following error when render customer.pug view.
error_console
I found that, if I add '\' before image path 'uploads\profileimage1520473825415.jpg', it displays image.
I tried many ways to do that did not work.
Please help me.
Cheers

Can't use Express to send data back to client more than once

In my app, I send a post request to the server with data containing a CSV file:
$.ajax({
type:"POST",
contentType: "application/json",
url:"/",
data: JSON.stringify({fileData:My_CSV_FILE}),
success: function(csvJson) {
console.log('in the done block!');
//can use csvJson in this handler
});
});
Note: I'm posting to the home route, and I am able to get a response with the data converted from the server. The problem is that whether I run on localhost or Heroku, I am only able to trigger the POST request once, then I have to restart the server (even if I refresh the page). So I know the issue is with my route somewhere:
UPDATED TO INCLUDE FULL SERVER FILE:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
var converter = new Converter({});
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.json(result);
}else {
res.json({error: 'Could not convert'});
}
})
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});
I'm using Express 4. Again, everything works, but only once. When I run Heroku logs, or check the console on localhost I get:
Error: Can't set headers after they are sent.
But I don't understand how I'm re-setting them.
If wanting to run on localhost, here is a link to the projects github: https://github.com/qctimes/calendar_export
You should move the converter instantiation to be done inside the app.post callback method. This way it will instantiate a new object at every request.
This is is how your code should be:
'use strict';
const express = require('express');
const csvtojson = require('csvtojson');
const PORT = process.env.PORT || 3000;
const bodyParser = require('body-parser');
const Converter = require('csvtojson').Converter;
let app = express();
app.use(bodyParser.json({limit: '300kb'}));
app.use(express.static(__dirname +'/public'));
app.post('/',function(req,res) {
var csvFile = (req.body.fileData);
var converter = new Converter({}); // instantiation is done here
converter.fromString(csvFile, function(err, result) {
if(!err) {
console.log(result);
res.send(result);
}else {
res.send({error: 'Could not convert'});
}
});
});
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`);
});

Node JS works on localhost, online 404

So i am trying to publish an node js app , but it is returning me 404 for my post calls . It works perfectly on localhost. This is my code :
app.js
var express = require('express');
var path = require('path');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = require('http').Server(app);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, '/')));
app.use('/', routes);
app.use('/users', users);
server.listen(process.env.PORT || 3000,function(){
console.log("Working on " + process.env.PORT);
});
module.exports = app;
This is my routes index.js
var express = require('express');
var request = require('request');
var path = require('path');
var bodyParser = require('body-parser');
var router = express.Router();
var app = express();
var jsonParser = bodyParser.json()
app.use(bodyParser.json())
var Connection = require('tedious').Connection;
var databaseConnection
var config = {}
var Connection = require('tedious').Connection;
var config = {
userName: 'asdasd',
password: 'password',
server: 'server',
options: {encrypt: true, database: 'asdasd'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
});
router.post('/call',jsonParser, function(req,res){
res.send('someresponse')
}
I am simply calling /call through ajax , but it keeps throwing 404 not found.
What am i doing wrong ? It doesnt make sense to me to work on localhost but not online.
If you are using express you cann start server directly with express.
app.listen(port)
If you want to do it with nodejs http you also have to set the port nodejs should listen to.
nodejs http
express app.listen
The problem was my auto generated web config was not doing its job , i have swaped it with another one i found on internet
https://github.com/projectkudu/kudu/wiki/Using-a-custom-web.config-for-Node-apps
Just changed from server.js to app.js

Resources