Node.js: Have node methods changed? - javascript

Something is not working very well with my code. I've just started with the first lines of code and installing the packages. Here is the code:
server.coffee
require 'coffee-script'
express = require 'express'
app = express()
app.get '/', (req, res) ->
res.send "Hello from express"
app.listen(3000)
console.log "Server is listening"
index.eco
<!DOCTYPE html>
<html lang="end">
<head>
<title>Our Page</title>
<body>
<h1>Our Index</h1>
</body>
</head>
</html>
First I have to say that the express.createServer() have change into express() but still, when I try to do change in the code
res.send "Hello from express"
to
res.render 'index.eco', layout: false
It doesn't work after I run the server. Any ideas?
package.json
{
"name": "coderacer",
"version": "0.0.0",
"description": "Example",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Ro",
"license": "BSD-2-Clause",
"dependencies": {
"coffee-script": "*",
"express": "*",
"eco": "*"
}
}

You aren't telling Express to use a template engine. In order to use a template engine such as Eco, you will also need Consolidate.js installed. Consolidate.js is a library adapter to allow other templating engines other than EJS and Jade to work with Express.
This is how you the libraries are used:
var express = require('express');
var app = express();
var cons = require('consolidate');
app.engine('eco', cons.eco);
app.get('/', function(req, res) {
res.render(__dirname + '/template.eco', {
layout: false
});
});
The Consolidate.js will automatically handle using require() on Eco, so that is the only library you need to initialize to use Eco. If you need a CoffeeScript version:
express = require("express")
app = express()
cons = require("consolidate")
app.engine "eco", cons.eco
app.get "/", (req, res) ->
res.render __dirname + "/template.eco", layout: false

Related

how to serve a vue js app with express and node?

i have a vue js project created with
vue create vue-js-client-crud
and built it with command
npm run build
file : router.js
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
export default new Router({
mode: "history",
routes: [
{
path: "/",
alias: "/products",
name: "tutorials",
component: () => import("./components/List")
},
{
path: "/products/:id",
name: "products-details",
component: () => import("./components/product")
},
{
path: "/add",
name: "add",
component: () => import("./components/Add")
}
]
});
ran into an example where , this vue js project is served by using express js via another project. so the set up is , create another nodewithExpress project, see sample package.json file and server.js. once this project is created, we create a views folder and then copy dist folder content from vue js project to this project. does this work and i didn't fully understand the set up. so in the express project , do we set up the routes exactly the same as we have in vue js project ? but this set up shouldn't work with spa pages , right?
{
"name": "nodeWithexpress",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1"
}
}
file : server.js
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.json({ message: "hello express." });
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`start server on port ${PORT}.`);
});

Uncaught TypeError: Failed to resolve module specifier (Node.js, Express, nact)

I'm building a simple app that demos the actor model using the Nact library.
The error I'm dealing with now is:
Uncaught TypeError: Failed to resolve module specifier "nact". Relative references must start with either "/", "./", or "../"
Here is package.json:
{
"name": "actor-model-with-nact-demo-020120",
"version": "1.0.0",
"description": "Adam's Actor Model with Nact Demo",
"main": "server.js",
"dependencies": {
"express": "^4.17.1",
"nact": "^7.2.2",
"nodemon": "^2.0.2"
},
"devDependencies": {},
"scripts": {
"dev": "nodemon ./server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Adam Dudley",
"license": "MIT"
}
Here is server.js:
const express = require('express')
const path = require('path')
const app = express()
const port = process.env.PORT || '8000'
app.use(express.static(__dirname + '/public'))
app.use('/static', express.static('./static/'))
app.get('/static', function(req, res) {
res.sendFile(path.join(__dirname + '/static/app.js'))
})
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html')
})
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`)
})
Here is index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Adam's Actor Model with Nact Demo</title>
</head>
<body>
<h1>Adam's Actor Model with Nact Demo</h1>
<script src="static/app.js" type="module"></script>
</body>
</html>
Here is app.js:
import { start, dispatch, stop, spawnStateless } from 'nact'
const system = start()
const greeter = spawnStateless(
system,
(msg, ctx) => console.log(`Hello ${msg.name}`),
'greeter'
)
dispatch(greeter, { name: 'World!' })
Author here. I'm not quite what the exact problem is here, but as it stands Nact is only officially supported on the server side. You may be able to get it to work in the browser, but you may have to polyfill setImmediate to do so.
As Nact is a commonjs module, you'll need a bundler like Parcel or Webpack to be able to convert the library into the appropriate module format.

Having trouble deploying an app to heroku through git

I am trying to create a simple node.js app on heroku. Here is my app.js:
console.log("Starting App")
const express = require('express')
const app = express()
const port = 3000
app.listen(process.env.PORT || port, () => console.log(`App listening on port ${port}!`))
app.get('/', (req,res) => {
res.sendFile(__dirname+'/public/index.html')
})
app.get('/style', (req,res) => {
res.sendFile(__dirname+'/public/main.css')
})
app.get('/script', (req,res) => {
res.sendFile(__dirname+'/public/script.js')
})
app.get('/changelog', (req,res) => {
res.sendFile(__dirname+'/public/changelog.txt')
})
here is my package.json file:
{
"name": "",
"version": "0.0.0",
"description": "",
"main": "/App.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
}
}
and here is my Procfile:
web: node app.js
I am deploying this to heroku via github, and whenever I run the program it gives me an error, saying Cannot find module '/app/app.js.' I have made everything lowercase and removed forward slashes. I still get this error: Error: Cannot find module '/app/app.js' Can anyone help?
In package.json, change "main": "/App.js" to "main": "app.js"
make sure package.json is at the same level as app.js
If app.js is in another folder, make sure to provide the full path from directory holding the package.json file.

Why is my app hanging on localhost?

I have recently built an MVC (well, more like a VC app) app in NodeJS and Express. Everything was working fine until I installed express-validator and pasted the middleware in the app file. Afterwards, localhost began hanging, with a GET / - - ms - - message in the console. I started a new app, reinstalled the modules, and copied and pasted the code. I still had the same issue, so I removed the express-validator middleware. Nothing changed.
App.js (entry point):
var config = require('./server/configure');
var express = require('express');
var app = express();
var app = config(app);
app.set('port', process.env.port || 3300);
app.set('views', __dirname + '/views');
app.listen(app.get('port'), function(req, res){
console.log('Server up: http://localhost:' + app.get('port'));
});
The routes file (/server/routes.js)
var express = require('express');
home = require('../controllers/home');
module.exports = function(app) {
router = express.Router();
router.get('/', home.home);
app.use(router);
};
The configure module (/server/configure.js)
var path = require('path'),
routes = require('./routes'),
ejs = require('ejs'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser({
uploadDir: path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('secret value'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
app.set('view engine', 'ejs');
return(app);
};
The home controller (/controllers/home.js):
module.exports = {
home: function(req, res) {
res.render('home');
}
};
The Package file (package.json):
{
"name": "krementcookdev",
"version": "1.0.0",
"description": "the krementcook web application",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Isaac Krementsov",
"license": "ISC",
"dependencies": {
"body-parser": "*",
"cookie-parser": "*",
"ejs": "*",
"errorhandler": "*",
"express": "*",
"express-handlebars": "*",
"express-validator": "*",
"method-override": "*",
"morgan": "*",
"path": "*"
},
"devDependencies": {}
}
Of course, I have a view file (home.ejs) in the /views directory. If you need to see it, let me know and I will add it to the post. Please do not close this a being a duplicate; I have checked similar problems and they mostly regard simple apps without routers or anything like that. I tried the solutions offered that applied to me, but none were relevant or productive.
Update: I did have specific versions in the package file, but I still had the same issue.
Try to use specific version (latest) of individual package in dependencies. for more detail Refer - https://docs.npmjs.com/files/package.json

Express .post routing method undefined

I'm new to nodejs and express and I can't seem to phantom as per why this method isn't resolved in Webstorm. The .get method returns fine, testing it with the .all method works fine aswell. I have no clue why the .post method is unresolved, node starts up fine but if I try to send a post request to it through Postman it just gives an error:
the Postman error
app.js
'use strict';
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var routes = require("./routes");
app.use(function (req, res, next) {
console.log(`${req.method} ${req.originalUrl}`);
next();
});
app.use(bodyParser.json());
app.use("/questions", routes);
// routes(app);
var port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Express is running at", port);
});
routes.js
'use strict';
var express = require("express");
var router = express.Router();
// GET /questions
// Route for getting all questions
router.get("/", function (req, res) {
res.json({
response: "You sent me an awesome GET request, thank you!"
});
});
// POST /questions
// Route for creating a question
router.post("/questions", function (req, res) {
res.json({
response: "You sent me an awesome POST request, thank you!"
});
body: req.body;
});
module.exports = router;
package.json
{
"name": "02-express-api",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.13.4"
}
}
router.post("/questions", should be router.post("/", for this to work; right now, that handler is responding to the URI /questions/questions since the router itself gets attached to handle URIs under /questions.

Categories