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
Related
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
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;
}));
So basically I've been trying to get https working with my socket.io
server code:
var express = require('express');
var app = express();
var httpsapp = express();
var https = require('https');
var fs = require("fs");
var server = https.createServer({
key: fs.readFileSync('key.pem').toString(),
cert: fs.readFileSync('cert.crt').toString(),
ca: fs.readFileSync('ca.pem').toString()
}, httpsapp);
var io = require('socket.io').listen(server);
var io = io.listen(8080);
(A whole bunch of socket.on's and one that sends one per second (they did work without https))
Client code:
var socket = io('https://server.com:8080', {secure: true});
I'm being filled to the brim with ERR_SSL_PROTOCOL_ERROR errors
Does anyone know how to fix this?
Edit: The certs are ones from cloudflare
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}`);
});
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